1

我有三张桌子

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
4

1 回答 1

1

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

其次,我感觉您的解决方案不会很好地扩展,因为您在所有三个表上都左连接。随着表的增长,我怀疑性能会很快下降。我会建议一个替代方案:

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 来展示您如何操纵组合结果。

于 2012-04-15T12:41:46.017 回答