Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql multi count() in one query

Tags:

mysql

count

I'm trying to count several joined tables but without any luck, what I get is the same numbers for every column (tUsers,tLists,tItems). My query is:

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

The result I want to get is

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

what modifications do i have to do to my query to get those results?

Cheers

like image 491
afarazit Avatar asked Feb 26 '23 11:02

afarazit


2 Answers

Try this

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
like image 55
Shakti Singh Avatar answered Mar 03 '23 21:03

Shakti Singh


You can do it by using sub query

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
like image 22
shankhan Avatar answered Mar 03 '23 21:03

shankhan