我有三张桌子
students: first_name, last_name, high_school_id, other_high_school
high_schols: id, title
other_high_schools: id, title, student_id
我想显示每个学生的列表,其中包含以下信息:名字、姓氏、高中
high_schools 表包含一个学生可以选择的预填高中列表,如果他们没有找到他们的高中,他们会在“其他高中”字段中填写他们的高中。当学生提交表单时,他们的信息被存储,将 students.other_high_school 字段设置为 1 并将他们的 id (student.id = other_high_school.student_id) 连同他们高中的名称一起存储到 other_high_schools 表 (other_high_school.title) 中。
select
first_name, last_name, hs.title as high_school
from
students s
left join
high_schools hs
on
s.high_school_id = hs.id
这将返回 first_name、last_name、high_school,但是否可以修改该查询以检测 students.other_high_school = 1,然后加入 other_high_school 而不是 high_schools 表?
这不起作用,但应该有助于解释我要完成的工作:
select
first_name, last_name, hs.title as high_school
from
students s
CASE s.other_high_school
WHEN 0 THEN
left join
high_schools hs
on
s.high_school_id = hs.id
WHEN 1 THEN
left join
other_high_school hs
ON
s.id = hs.student_id
ELSE
left join
other_high_school hs
ON
s.id = hs.student_id
END CASE
解决了
select
first_name, last_name,
IF(s.other_high_school = 1, ohs.title, hs.title) high_school
from
students s
left join
high_schools hs
on
s.high_school_id = hs.id
left join
other_high_schools ohs
on
s.id = ohs.student_id