2016-09-15 86 views
1

我有两个表: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 

有人可以帮我解决这个问题吗?

回答

1

select (t1.car_price + coalesce(extra_price, 0)) as start_price 
 
from tcars t1 
 
left join (select id_car,sum(price) as extra_price from tcar_optionals 
 
where opt_included and price > 0 group by 1) q1 on q1.id_car = t1.id 
 
where t1.id=$1

2

其中条款有效地把你的外在条件q1.id_car=1加入到内部联接,因为行不匹配连接条件q1.id_car将是无效和比较=1将再次删除这些行。

您将需要它放入JOIN条件 - 但你已经对id_car条件派生表(“Q1”),你不需要也无妨。

的另一种可能性是从tcars表上的相应值过滤:where t1.id = 1


编辑

通过在t2表移动条件下的连接条件你得到你想要什么:

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 
      and t2.opt_included and t2.price > 0 --<< conditions for tcar_optionals go here 
where t1.id = 1 --<< limit the car you want to see 
group by t1.id; 

if id i s被定义为tcars中的主键,那么group by t1.id就足够了。

在这里看到的例子:http://rextester.com/YOYF30261

+0

我需要q1.id_car = 1;对于返回特定车辆的价格,如果我删除这条线路,查询将返回我的分贝中所有车辆的价格 – Kuzuri

+0

@Kuzuri:您可以使用'where t1.id = 1将总体结果限制为仅一辆车' –

+0

我知道,如果我没有包含任选项,我需要从这个查询中返回车的价格。 假设我有两辆车:tcar中id = 1,id = 2,tcar_specs中id_car = 1,id_car = 2。第一辆车的价格是1000,我有两个包括可选项(第一个价格是100和第二个150),查询将返回1250,第二辆车的(id_car = 2)价格是900,我没有包含可选项,应该返回900但它不,它什么都不返回。 – Kuzuri

2

你应该首先加入与该第二表中的所有条件和汇总值的表(加入)的结果,即G:

select id, coalesce(car_price, 0)+ coalesce(sum(price), 0) total_price 
from tcars 
left join tcar_optionals on id = id_car and spec_included 
-- where id = 1 
group by id, car_price 
+0

同样的结果,没有行,如果我没有包括可选项 – Kuzuri

+0

这是不可能的。我在查询中改变了一些内容吗?参见[SqlFiddle](http://sqlfiddle.com/#!15/07296/1) – klin