簡體   English   中英

SQL-從一些聯接中獲取表的行數

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

在該數據庫中,有4個相關表。 (還顯示相關字段)

導師:身份證,姓名

tutor_locations: id,tutor_id,location_id

位置: ID,名稱,region_id

地區: ID,名稱

我的目標是要列出一個地區列表,其中包含每個地區有多少名教師。

由於數據庫設計的原因,存在一個中間表tutor_locations,其中的行表示某個教師在某個位置。 一個地區可以有很多位置,但我只希望該地區的教師人數,而不是每個位置的教師人數。

所需輸出的圖像: 帶有教師人數的區域列表

我能夠獲得每個區域的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;

是否有可能使用這樣的聯接來獲得導師的數量?

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;

請在下面的查詢中使用:

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