Mysql Join返回重复值

时间:2018-01-28 20:35:25

标签: mysql sql

我有两个表时间表和主题,我需要来自主题表的id,subject_name,而不是在特定部分的时间表中使用。

时间表 timetable 主题表

subject

但它会返回多个值,如下图所示。 result

我正在使用此查询

SELECT subject.id, subject.subject_name 
FROM timetable 
LEFT JOIN subject 
ON timetable.subject_id != subject.id AND timetable.class_id = subject.class_id 
WHERE timetable.class_id = 1 and timetable.section_id =1

2 个答案:

答案 0 :(得分:1)

我仍然认为这是一个重复的问题。虽然你的问题有点复杂。所以试试这个:

SELECT subject.id, subject.subject_name 
FROM subject
LEFT JOIN timetable 
  ON  timetable.subject_id = subject.id
  AND timetable.class_id   = subject.class_id 
  AND timetable.section_id = 1
WHERE subject.class_id = 1
  AND timetable.id IS NULL

答案 1 :(得分:0)

这个简单的查询有效。

SELECT id, subject_name FROM subject WHERE class_id = 1 
AND id NOT IN (SELECT subject_id from timetable where section_id=1)