什么,我想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