如果表中的字段中包含1,则需要检查其他表

时间:2012-04-13 17:15:39

标签: mysql

我有三张桌子

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

1 个答案:

答案 0 :(得分:1)

首先,我会重新考虑您的架构。你真的需要在不同的表中使用high_schools和other_high_schools吗?或者你可以在一张桌子上加一张额外的旗帜,看看它是默认的高中还是用户增加的高中?

其次,我觉得你的解决方案不能很好地扩展,因为你在所有三个表上都是LEFT JOIN。随着表格的增长,我怀疑性能会很快降低。我会建议一个替代方案:

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

使用正确的INDEX,这应该与您的解决方案一样快,并且可能会更好地扩展(但这完全取决于您的实际数据集的形状)。我添加了一个ORDER BY来展示你如何操纵组合结果。