2014-11-20 44 views
0

什么,我想archieve:如果表中的行存在,那么在SQL中使用另一个表值

获取正确总和已取消用户ID 2002的订单总金额。

一些预配置信息:

我有deals它有它的价格在deals.price和其ID在deals.ID

然后我有orders有外键deals.ID

运行该SQL:

select SUM(deals.price), orders.* from orders 
JOIN deals ON deals.ID = orders.deal_id 
where orders.user_id = 2002 
and orders.cancelled = 1 

作品就好了。

这里是我卡住:

作为除了交易,每个交易都有产品与自己的价格。

表称为deal_products,deal_products.price保存价格,deal_products.product_id具有它的ID。

一个为了连接到一个交易产品的另一个表称为order_products,其中order_products.product_id = deal_products.product_id

综上所述:我愿做的是包括如果上面的SQL内。

如果订单在order_products中有一行,请获取order_products.product_id并查找deal_products(price)中的价格,并在SUM()'ing时使用它而不是deals.price。

如果没有行,它应该使用deals.price。

这怎么实现?要先查看另一个表中是否有条目,然后再查找第三个表并获取要使用的值?

回答

3

您可以使用COALESCE + LEFT JOIN:

select SUM(coalesce(dp.price, d.price)), o.* 
from orders o JOIN deals d ON d.ID = o.deal_id 
       LEFT JOIN order_products op on op.order_id = o.id 
       LEFT JOIN deal_products dp on op.product_id = dp.product_id 
where o.user_id = 2002 and o.cancelled = 1 
group by ...; 

COALESCE函数首先返回不为空操作

LEFT [OUTER] JOIN = [INNER] JOIN +所有左侧的LEFT JOIN关键字,这别结构的行t匹配正确结构中的ON子句。

+0

太棒了!谢谢你告诉我这件事。但我忘了补充一点,如果它不是0,它应该只用于dp.price? – Karem 2014-11-20 19:56:46

+0

@Karem使用SUM(当dp.price> 0时,则dp.price或d.price结束)。 – Multisync 2014-11-20 19:58:06

相关问题