简体   繁体   中英

Left outer join with count, on 3 tables not returning all rows from left table

I have these 3 tables:

Areas - id, name
Persons - id, area_id
Special_Persons - id_person, date

I'd like to produce a list of all Areas, followed by a count of Special Persons in each area, including Areas with no Special Persons.

If I do a left join of Areas and Persons, like this:

select a.id as idArea, count(p.id) as count 
from areas a 
left join persons p on p.area_id = a.id
group by a.id;

This works just fine; Areas that have no Persons show up, and have a count of 0.

What I am not clear on is how to do the same thing with the special_persons table, which currently only has 2 entries, both in the same Area.

I have tried the following:

select a.id as idArea, count(sp.id_person) as count
from special_persons sp, areas a
left join persons p on p.area_id = a.id 
where p.area_id = a.id 
and sp.id_person = p.id 
group by a.id;

And it only returns 1 row, with the Area that happens to have 2 Special Persons in it, and a count of 2.

To continue getting a list of all areas, do I need to use a sub-query? Another join? I'm not sure how to go about it.

You can add another left join to the Special_Persons table:

select a.id as idArea, count(p.id), count(sp.id_person) 
from areas a 
left join persons p on p.area_id = a.id
left join special_persons sp on sp.id_person = p.id
group by a.id;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM