没有订单的客户

时间:2015-10-02 18:39:38

标签: php mysql

我需要获得订单数量的客户列表。实际上使用下面的查询来获得客户的订单,如:

+-------+----------------+
| JAMES | 2 orders total |
| PAUL  | 6 orders total |
+-------+----------------+

为此,我使用此查询:

SELECT *
FROM mod_users    
INNER JOIN (SELECT order_user_id, count(*) as order_qty
            FROM mod_orders
            GROUP BY user_order_id) AS order_qty
  ON mod_users.user_id = order_qty.order_user_id;

现在,我想让用户没有订单:

+-------+----------------+
| JAMES | 2 orders total |
| PAUL  | 6 orders total |
| FRANK | 0 orders total |
+-------+----------------+

任何人都可以帮忙进行查询吗?

1 个答案:

答案 0 :(得分:2)

使用LEFT JOIN代替INNER JOIN

SELECT mod_users.user_id, COALESCE(order_qty, 0) AS ordersCount
FROM mod_users    
LEFT JOIN (SELECT order_user_id, count(*) as order_qty
            FROM mod_orders
            GROUP BY user_order_id) AS order_qty
  ON mod_users.user_id = order_qty.order_user_id;

如果mod_orders未包含特定用户的任何记录,则order_qty对于此用户NULL将归LEFT JOINCOALESCE将此NULL值转换为0