Mysql在简单连接

时间:2015-08-24 09:55:35

标签: mysql join

我有2个表:coursesection,如sqlfiddle

所示

我需要为每个课程的部分选择'starttime' (or null)。 有些课程没有“部分”条目。

查询:

select section.id, section.course, section.section, IFNULL(schedule.starttime, "null")
from section
join schedule on schedule.courseid = section.course
where course = 3 and section.section > 0

返回有许多重复的条目,就像在连接表中一样。

id      course  section IFNULL(schedule.starttime, "null")
7       3       1       1440021600
7       3       1       1440021620
7       3       1       1440021640
8       3       2       1440021600
8       3       2       1440021620
8       3       2       1440021640
9       3       3       1440021600
9       3       3       1440021620
9       3       3       1440021640

当我期待:

id      course  section IFNULL(schedule.starttime, "null")
7       3       1       1440021600
8       3       2       1440021620
9       3       3       1440021640
10      3       4       null
11      3       5       null

我尝试了DISTINCTGROUP BY的不同组合,但没有成功。

2 个答案:

答案 0 :(得分:2)

尝试:

SELECT section.id, section.course, section.section, IFNULL(schedule.starttime, "null")
FROM section
LEFT JOIN schedule ON schedule.courseid = section.course AND schedule.id = section.section
WHERE course = 3 AND section.section > 0

答案 1 :(得分:1)

您可以使用left join,然后使用schedule.sectionidsection.id

select section.id, section.course, section.section, IFNULL(schedule.starttime, "")
from section
LEFT JOIN schedule ON schedule.sectionid = section.id
where course = 3 and section.section > 0;

<强> SEE DEMO