0

I have 3 tables user, person and company.
the user_id is a foreign key in both person and company tables.
what I want to do is to count how many persons and companies are related to each user, so I did the following query:

select u.id , u.username, count(c.user_id) as count_company, count(p.user_id) as count_people
from user u left join company c on (u.id = c.user_id)
left join person p on (u.id = p.user_id)
group by u.id, u.username

but I'm getting wrong result!!
This is the result I get:
enter image description here

however, when I try to count only the companies related to each user using this query:

select u.id , u.username, count(c.staff_user_id) as count_company
from fos_user u left join company c on (u.id = c.staff_user_id)
group by u.id, u.username

I get this result:
enter image description here
what am I missing here ?

2 Answers 2

3

If a user is related to multiple companies and/or multiple persons, then you always count the cross join of them - Which is then the number of companies multiplied with the number of persons.

To solve that problem (in your case) I would just use subqueries:

select u.id, u.username, 
    (select count(*) from company c where u.id = c.user_id) as count_company,
    (select count(*) from person p  where u.id = p.user_id) as count_people
from user u

Note that a double join like in your query is from relational point of view (in most cases) just wrong.

Sign up to request clarification or add additional context in comments.

Comments

0

seems you need the distinct count

select u.id 
    , u.username
    , count(distinct c.user_id) as count_company
    , count(distinct p.user_id) as count_people
from user u 
left join company c on (u.id = c.user_id)
left join person p on (u.id = p.user_id)
group by u.id, u.username

count(col) count the not null values for col in relation ... count(distinct col) count the distinct value for col1

Comments

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.