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:
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
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.