我需要获得订单数量的客户列表。实际上使用下面的查询来获得客户的订单,如:
+-------+----------------+
| 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 |
+-------+----------------+
任何人都可以帮忙进行查询吗?
答案 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 JOIN
。 COALESCE
将此NULL
值转换为0
。