我有三个表
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
最佳答案
首先,我会重新考虑您的架构。您真的需要不同表中的 high_schools 和 other_high_schools 吗?或者您是否可以在一张表中添加一个额外的标志,说明它是默认高中还是用户添加的高中?
其次,我感觉您的解决方案不会很好地扩展,因为您在所有三个表上都采用 LEFT JOINing。随着表的增长,我怀疑性能会很快下降。我会建议一个替代方案:
SELECT first_name, last_name,title
FROM (
SELECT first_name, last_name,title
FROM students s
INNER JOIN high_schools hs ON s.high_school_id = hs.id
WHERE s.other_high_school=0
UNION
SELECT first_name, last_name,title
FROM students s
INNER JOIN other_high_schools ohs ON s.high_school_id = ohs.id
WHERE s.other_high_school=1
) AS combined_schools
ORDER BY last_name,first_name
使用正确的索引,这应该与您的解决方案一样快,并且可能会更好地扩展(但这完全取决于您的真实数据集的形状)。我添加了一个 ORDER BY 来展示您可以如何操作组合结果。
关于mysql - 如果表中的字段中有 1,则需要检查其他表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10145307/