使用LEFT JOIN和2个不同的查询GROUP BY

时间:2013-05-21 12:35:50

标签: php sql count group-by

我的第一个SQL查询是:

SELECT username,COUNT(username) as total_active_users FROM users WHERE active = '1' GROUP BY referrer //  $act_user

计算每个引荐来源的活跃用户

第二个sql查询是:

SELECT COUNT(orders) as total_user_orders FROM users_orders GROUP BY $act_user['username'] // the username from the first query.

计算我从第一个查询中获得的每个用户的总订单数

我正在尝试使用LEFT JOIN来计算至少包含1个订单的活跃用户

问题是:我有2个不同的GROUP BY,第一个是“推荐人”,第二个是“用户名”

我正在尝试做类似的事情:

SELECT u.username, COUNT(u.username) as total_active_users, COUNT(b.orders) as 
total_user_orders FROM users u LEFT JOIN users_orders b on u.username = b.username
WHERE u.active = '1' AND total_user_orders >= '1' GROUP BY (u.referrer for u) and (b.username for b)

请问好吗?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

SELECT 
  a.username, 
  COUNT(u.username) as total_active_users, 
  COUNT(b.orders) as total_user_orders 
FROM
(
   SELECT username FROM users_orders WHERE total_user_orders >= '1' 
   UNION ALL
   SELECT username FROM users        WHERE u.active = '1' 
) AS a
LEFT JOIN users        AS u ON a.username = u.username
LEFT JOIN users_orders AS b on u.username = b.username
GROUP BY a.username;

答案 1 :(得分:0)

假设用户名是唯一的,并且用户至少有一个订单意味着与users_orders表中至少有一行相同,那么您可以执行以下操作:

SELECT
  u.referrer,
  COUNT(DISTINCT u.username) AS usercount
FROM users u
INNER JOIN users_orders uo ON u.username = uo.username
WHERE u.active = 1
;

usersusers_orders之间的联接充当过滤器(除了active状态之外)。它可能会产生重复的用户名,但COUNT(DISTINCT)只会计算唯一的条目。