我想写一个SQL Query,它应该返回在特定城镇教授特定主题的导师总数。
这是我的查询
SELECT COUNT(*)
FROM `tutor_main` tm
JOIN `tutor_subjects` ts ON tm.`tutor_id` = ts.`tutor_id`
JOIN `sub_subjects` ss ON ss.`subs_id` = ts.`subs_id`
JOIN `town` tt ON tm.`town_id` = tt.`town_id`
JOIN `subject_level` sl ON sl.`sub_level_id` = ts.`sub_level_id`
WHERE ts.`subs_id` = 1
AND tm.`town_id` = 1
此处tutor_main
作为将town_id
存储为外键的主表。
sub_subjects
作为主要主题表,subject_level表存储主题级别。类似地,tutor_subjects
表存储了tutor_id,subs_id和sub_level_id的键。
这是tutor_subjects
表的屏幕截图:
请注意,所有导师的town_id
为1.
现在当我运行查询时,它在输出中给出了8。正确的输出应该是5,因为有5位教师正在教授id为1的教师,他们都来自身份1的城镇。
请帮助。
答案 0 :(得分:1)
SELECT COUNT(DISTINCT tm.`tutor_id`)
FROM `tutor_main` tm
JOIN `tutor_subjects` ts ON tm.`tutor_id` = ts.`tutor_id`
JOIN `sub_subjects` ss ON ss.`subs_id` = ts.`subs_id`
JOIN `town` tt ON tm.`town_id` = tt.`town_id`
JOIN `subject_level` sl ON sl.`sub_level_id` = ts.`sub_level_id`
WHERE ts.`subs_id` = 1
AND tm.`town_id` = 1