左连接计数忽略左表列从计数

时间:2018-05-16 06:33:21

标签: php mysql database

我有两张桌子......首先是order_idorder_statususer_id ....第二张桌子有order_idproduct_idproduct_quantity如下所示

第一桌

    order_id | order_status | user_id
    ----------------------------
    1        | 5            | 2
    2        | 1            | 1
    3        | 5            | 1
    4        | 5            | 1

第二桌

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,其中order_status = 5,sum(quantity)group by user_id

MY TRY

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有3个实例按用户ID 1传递的订单。

任何建议或解决方案......我很久以来就陷入困境:(

谢谢

1 个答案:

答案 0 :(得分: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

另外,在IF内使用COUNT功能,如下所示:

COUNT(IF(h.order_status = 5,1,0)) AS total_orders

没有任何意义,因为h.order_status 总是等于5,因为WHERE子句:

WHERE h.order_status = 5

Demo here

相关问题