2014-11-20 45 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

相關問題