4

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

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Shakti Singh, that query gives me the results I wanted. I just added "Count(DISTINCT u.userID) as tUsers". I didn't knew about the existence of DISTINCT, thank you for that.
This worked for something I'm working on as well. My only question is why is the distinct needed for each count column?
3

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

2 Comments

hi shankhan, i won't insert "YourUserID" using an application, "YourUserID" is coming from the JOINs. Can you please modify your query so it does that?
hmm in that case you will have to write join in each sub query and it will be little costly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.