我想提取一些数据。
以下是设置:
[学校]可以有多个[学期]。每个[学校]只有一个[学期]可以活动。
每个表格的简化字段:
“school_semester”表包含特定学校/学期的信息。 (STARTDATE,结束日期,等等)。
无论如何,我只是试图拉开所有学校,在这个问题中我想看到学校目前活跃的学期。
到目前为止,这是我的查询:
SELECT *, `school`.`name` as school_name
FROM (`school`)
LEFT JOIN `school_semester` ON `school`.`id` = `school_semester`.`school_id`
LEFT JOIN `semester` ON `semester`.`id` = `school_semester`.`semester_id`
ORDER BY `school_semester`.`active`
问题:
如果学校有活跃的学期,但如果没有,则会显示一个可能被标记为非活动的学期。如果我添加语句WHERE school_semester
。active
= 1,则它排除了没有活跃学期的学校..
任何指针?
答案 0 :(得分:2)
移动加入条件:
SELECT *, `school`.`name` as school_name
FROM (`school`)
LEFT JOIN `school_semester` ON
`school`.`id` = `school_semester`.`school_id` AND
`school_semester`.`active`
LEFT JOIN `semester` ON `semester`.`id` = `school_semester`.`semester_id`
这样,只有活跃的学期才会加入到结果中。
答案 1 :(得分:0)
在加入条件中添加active=1
。
SELECT *, `school`.`name` as school_name
FROM (`school`)
LEFT JOIN `school_semester` ON `school`.`id` = `school_semester`.`school_id`
AND `school_semester`.`active` = 1
LEFT JOIN `semester` ON `semester`.`id` = `school_semester`.`semester_id`
ORDER BY `school_semester`.`active`