在此数据库中,有4个相关的表。 (还显示相关字段)
导师: ID,名称
教师位置: id,tutor_id,location_id
位置: ID,名称,region_id
地区: ID,名称
我的目标是要列出一个地区列表,其中包含每个地区有多少名教师。
由于数据库的设计,存在一个中间表tutor_locations,其中的行表示某个教师在某个位置。一个地区可以有很多位置,但我只希望该地区的老师人数,而不是每个位置的老师人数。
所需输出的图像: List of regions with tutor count
我能够获得每个区域的tutor_locations行数,但是我很难获得每个区域的实际导师数。
我的查询是:
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;
是否可以使用这样的联接来获得大量的导师?
答案 0 :(得分:0)
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;
答案 1 :(得分:0)
请在下面的查询中使用
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