SQL查询没有给出确切的结果

时间:2016-08-01 12:04:17

标签: mysql sql count

我想写一个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表的屏幕截图:

enter image description here

请注意,所有导师的town_id为1.

现在当我运行查询时,它在输出中给出了8。正确的输出应该是5,因为有5位教师正在教授id为1的教师,他们都来自身份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