将查询合并为1以进行排序

时间:2014-01-06 16:35:41

标签: mysql sql

这是获取用户的查询

SELECT * FROM users

然后对于每个用户,我需要获取信息

SELECT COUNT(user_id) FROM users WHERE refer_id='{$users['user_id']}' 
SELECT COUNT(user_id), SUM(amount) FROM visitors WHERE user_id='{$users['user_id']}' 
SELECT COUNT(user_id) FROM sales WHERE user_id='{$users['user_id']}' 

第一个查询中的user_id统一了它们。我需要按每次计数合并这些查询

1 个答案:

答案 0 :(得分:0)

您可以使用嵌套子查询执行此操作:

select u.user_id, count(*) as numusers,
       (SELECT COUNT(user_id), FROM visitors v WHERE v.user_id = u.user_id) as NumVisitors,
       (SELECT SUM(amount) FROM visitors v WHERE v.user_id = u.user_id) as VisitorAmount,
       (SELECT COUNT(user_id) FROM sales s WHERE s.user_id = u.user_id) as NumSales
from users u
group by u.user_id;

您也可以通过加入预先汇总的查询来执行此操作:

select u.user_id, v.NumVisitors, v.VisitorAmount, s.NumSales
from (select u.user_id, count(*) as NumUsers
      from users u
      group by u.user_id
     ) u left outer join
     (select v.user_id, count(user_id) as NumVisitors, sum(amount) as VisitorAmount
      from visitors v
      group by v.user_id
     ) v
     on u.user_id = v.visitor_id left outer join
     (select s.user_id, count(user_id) as NumSales
      from sales s
      group by s.user_id
     ) s
     on s.user_id = u.user_id;