什麼,我想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。
這怎麼實現?要先查看另一個表中是否有條目,然後再查找第三個表並獲取要使用的值?
太棒了!謝謝你告訴我這件事。但我忘了補充一點,如果它不是0,它應該只用於dp.price? – Karem 2014-11-20 19:56:46
@Karem使用SUM(當dp.price> 0時,則dp.price或d.price結束)。 – Multisync 2014-11-20 19:58:06