[英]SQL Join Constraint Column on Another Joined Table
So practically I have 3 tables: 所以实际上我有3张桌子:
products 产品展示
id ID
orders 命令
id ID
status 状态
order_items order_items
id ID
order_id order_id
product_id product_id
quantity 数量
So I want to query by products table as the main one. 所以我想按产品表作为主要查询。 I want to know how many each one has been ordered, hence
我想知道每个人订购了多少,因此
SELECT products.*, SUM(order_items.quantity) AS sale_count
FROM products
LEFT JOIN order_items ON products.id = order_items.product_id
GROUP BY products.id
Everything works fine, no problem. 一切正常,没问题。 But this query will count any
order_items
for each row, now I want to count only if the order status is done
. 但是此查询将对每一行的任何
order_items
进行计数,现在我只想在done
订单状态后进行计数。 But the problem is to get the status of that order_items
you need to reference orders
right? 但是问题是要获取您需要引用
orders
order_items
的状态正确吗?
SELECT products.*, SUM(order_items.quantity) AS sale_count
FROM products
LEFT JOIN order_items ON products.id = order_items.product_id
LEFT JOIN orders ON order_items.order_id = orders.id AND orders.status = 'done'
GROUP BY products.id
But this doesn't make a constraint on the order_items instead only order which has the status of done
will be shown in the table else NULL. 但是,这并没有使对ORDER_ITEMS,而不是只具有的地位顺序的约束
done
将在其他表显示NULL来。
How to approach this problem? 如何解决这个问题? Thank you for your kind help.
感谢您的热心帮助。 I really appreciate it!!
我真的很感激!!
I think you just want conditional aggregation: 我认为您只需要条件聚合:
SELECT p.*,
SUM(CASE WHEN o.status = 'done' THEN order_items.quantity END) AS sale_count
FROM products p LEFT JOIN
order_items oi
ON p.id = oi.product_id LEFT JOIN
orders o
ON oi.order_id = o.id
GROUP BY p.id;
I moved the 'done'
condition to a case
statement. 我将
'done'
条件移到了case
陈述中。 You can leave it in the on
clause as well, if you like. 如果愿意,也可以将其保留在
on
子句中。 I just think this logic is more explicit about your intention. 我只是认为这种逻辑对您的意图更为明确。
It's not 100% clear to me what you are asking, but I think you are asking how to count orders for which the order status is done without throwing out results for which the order status is not done. 我不清楚您要问的是什么,但我想您是在问如何计算已完成订单状态的订单,而不抛出未完成订单状态的结果,这并不是100%清楚的。 If so, then the following should work:
如果是这样,那么以下应该工作:
SELECT products.*,
SUM(CASE WHEN orders.status = 'done'
THEN order_items.quantity
ELSE 0 END) AS sale_count
FROM products
LEFT JOIN order_items
ON products.id = order_items.product_id
LEFT JOIN orders
ON order_items.order_id = orders.id
GROUP BY products.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.