简体   繁体   中英

SQL - Get row count of table from a few joins away

In this database there are 4 relevant tables. (Also showing relevant fields)

tutors: id, name

tutor_locations: id, tutor_id, location_id

locations: id, name, region_id

regions: id, name

My aim is to have a list of regions with a count of how many tutors are in each region.

Due to the database design, there is an intermediary table tutor_locations where rows represent a tutor being in a certain location. A region can have many locations but I only want the tutor count for the region, not the tutor count per location.

An image of the desired output: List of regions with tutor count

I'm able to get a count of tutor_locations rows per region, but I'm having trouble getting a count of the actual tutors per region.

My query is:

SELECT regions.name as region, COUNT(*) as tutor_count
FROM regions
LEFT JOIN locations ON locations.region_id = regions.id
LEFT JOIN tutor_locations ON locations.id = tutorlocations.location_id
LEFT JOIN tutors ON tutors.id = tutor_locations.tutor_id
GROUP BY region;

Is it possible to get a count of tutors using joins like this?

SELECT locations.region_id, regions.name as region, COUNT(*) as tutor_count
FROM regions
LEFT JOIN locations ON locations.region_id = regions.id
LEFT JOIN tutor_locations ON locations.id = tutorlocations.location_id
LEFT JOIN tutors ON tutors.id = tutor_locations.tutor_id
GROUP BY region, locations.region_id;

Please use below Query:

SELECT r.id AS region_id, r.name as region_name, COUNT(distinct t.id) as tutor_count
FROM regions r
INNER JOIN locations l ON l.region_id = r.id
INNER JOIN tutor_locations tl ON l.id = tl.location_id
INNER JOIN tutors t ON t.id = tl.tutor_id
GROUP BY r.id, r.name

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