我有两个表:PostgreSQL的COALESCE不设置默认值
tcars
id | name | car_price
----|---------------------|------------
1 |First_car_name | 1000
2 |Second_car_name | 1200
tcar_optionals
id | id_car | spec | opt_included |price
----|----------|------|-------------------------
1 | 2 |Spec1 | true | 500
2 | 2 |Spec2 | true | 100
3 | 2 |Spec3 | false | 500
4 | 2 |Spec4 | true | 0
5 | 1 |Spec5 | false | 500
6 | 1 |Spec6 | true | 0
而下面的查询:
select t1.id, coalesce(t1.car_price, 0)+ coalesce(sum(t2.price), 0) as total_price
from tcars t1
left join tcar_optionals t2 on t2.id_car = t1.id
where t2.opt_included and t2.price>0 and t1.id=?
group by t1.id, t1.car_price
它从tcars和total_price(car_price +包含价格> 0的optionals的价格)返回id。
实施例:
为t1.id=2
回报:
id | total_price
----|------------
2 | 1800
当我有价> 0不包括自选,例如t1.id = 1
什么它返回出现问题:
id | total_price
----|------------
我需要的仅仅是返回t1.car_price作为total_价格如果没有包含可选价格> 0:
id | total_price
----|------------
1 | 1000
有人可以帮我解决这个问题吗?
我需要q1.id_car = 1;对于返回特定车辆的价格,如果我删除这条线路,查询将返回我的分贝中所有车辆的价格 – Kuzuri
@Kuzuri:您可以使用'where t1.id = 1将总体结果限制为仅一辆车' –
我知道,如果我没有包含任选项,我需要从这个查询中返回车的价格。 假设我有两辆车:tcar中id = 1,id = 2,tcar_specs中id_car = 1,id_car = 2。第一辆车的价格是1000,我有两个包括可选项(第一个价格是100和第二个150),查询将返回1250,第二辆车的(id_car = 2)价格是900,我没有包含可选项,应该返回900但它不,它什么都不返回。 – Kuzuri