一个查询中的mysql multi count()

时间:2010-12-31 07:08:03

标签: mysql count

我正在尝试计算几个连接表,但没有任何运气,我得到的是每列(tUsers,tLists,tItems)的相同数字。我的疑问是:

select COUNT(users.*) as tUsers,
       COUNT(lists.*) as tLists,
       COUNT(items.*) as tItems,
       companyName
    from users as c
    join lists as l
    on c.userID = l.userID
    join items as i
    on c.userID = i.userID
    group by companyID

我想得到的结果是

---------------------------------------------
 #  | CompanyName | tUsers | tlists | tItems 
 1  | RealCoName  |    5   |   2    |   15
---------------------------------------------

我必须对查询进行哪些修改才能获得这些结果?

干杯

2 个答案:

答案 0 :(得分:5)

试试这个

SELECT u.userID, companyName, 
       Count(DISTINCT l.listid) as tLists, Count(DISTINCT i.items) as tItems
 FROM users u
   LEFT JOIN lists l ON u.userID=l.userID
   LEFT JOIN items i ON u.userID=i.userID 
GROUP BY u.companyID

答案 1 :(得分:3)

您可以使用子查询

来完成
select (select count(*) from users where userID=YourUserID) tUsers,
       (select count(*) from lists where userID=YourUserID) as tLists,
       (select count(*) from items where userID=YourUserID) as tItems,
       companyName
    from company group by companyID