简体   繁体   English

SQL-从一些联接中获取表的行数

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

In this database there are 4 relevant tables. 在该数据库中,有4个相关表。 (Also showing relevant fields) (还显示相关字段)

tutors: id, name 导师:身份证,姓名

tutor_locations: id, tutor_id, location_id tutor_locations: id,tutor_id,location_id

locations: id, name, region_id 位置: ID,名称,region_id

regions: id, name 地区: ID,名称

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. 由于数据库设计的原因,存在一个中间表tutor_locations,其中的行表示某个教师在某个位置。 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. 我能够获得每个区域的tutor_locations行数,但是我很难获得每个区域的实际导师数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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