我有两个表 ...第一个有 order_id
、order_status
和 user_id
...第二个表有 order_id
和 product_id
, product_quantity
如下
第一个表
order_id | order_status | user_id
----------------------------
1 | 5 | 2
2 | 1 | 1
3 | 5 | 1
4 | 5 | 1
第二张 table
order_id | product_id | quantity
----------------------------
1 | 200 | 4
2 | 201 | 2
2 | 200 | 1
2 | 207 | 4
3 | 201 | 1
3 | 200 | 6
4 | 201 | 8
我想得到
user_id | Total_orders | quantity
----------------------------
1 | 2 | 15
2 | 1 | 4
获取 user_id where order_status = 5 and sum(quantity) group by user_id
我的尝试
SELECT h.user_id
, COUNT(IF(h.order_status = 5,1,0)) AS total_orders
, SUM(o.quantity) AS quantity
FROM table1 h
LEFT
JOIN table2 o
ON o.order_id = h.order_id
WHERE h.order_status = 5
GROUP
BY h.user_id
但是,它给我的结果是计算左表中 order_id 的所有实例,例如...状态为 5 的 user_id 1 的总订单数为 2,但我的查询返回 3 作为计数 (order_id
) bcz是用户 id 1 传递的订单的 3 个实例。
任何建议或解决方案......我被困了很长时间:(
谢谢
最佳答案
您需要计算order_id
的不同 出现次数:
SELECT h.user_id,
COUNT(DISTINCT h.order_id) AS total_orders,
SUM(o.quantity) AS quantity
FROM table1 h
LEFT JOIN table2 o ON o.order_id=h.order_id
WHERE h.order_status = 5
GROUP BY h.user_id
此外,在 COUNT
中使用 IF
函数,如下所示:
COUNT(IF(h.order_status = 5,1,0)) AS total_orders
没有意义,因为 h.order_status
总是 等于 5,因为 WHERE
子句:
WHERE h.order_status = 5
关于php - 左连接计数忽略左表列计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50363881/