mysql:合并相关表时显示所有可用数据,即使引用外键为空

col17t5w  于 2023-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(351)

我有以下问题

SELECT s.id AS id, s.grade_id as grade_id, g.name as grade_name, s.name AS name, s.scheduled_days as scheduled_days, s.period_id as period_id, p.name as period_name, s.start_time as start_time, s.end_time as end_time, s.teacher_id as teacher_id, u.name as teacher_name, s.classroom_id as classroom_id, c.name as classroom_name
FROM sections s, grades g, periods p, teachers t, users u, classrooms c
WHERE s.grade_id = g.id AND s.period_id = p.id AND s.classroom_id = c.id AND s.teacher_id = t.id AND t.user_id = u.id

这里有可能 teacher_id 以及 classroom_id 节表中的外键为空。但是,如果任何一个外键为null,mysql就会从所有相关表中排除整列。
我如何修改查询,以便mysql将显示来自sections表的数据,即使这些键为null。

o7jaxewo

o7jaxewo1#

你需要使用外部连接。
首先,您需要使用现代的join语法,这种语法从1992年就开始使用了。使用此语法可以 LEFT [OUTER] JOIN ,例如:

SELECT
  s.id AS id, s.grade_id as grade_id, g.name as grade_name, s.name AS name, 
  s.scheduled_days as scheduled_days, s.period_id as period_id,
  p.name as period_name, s.start_time as start_time, 
  s.end_time as end_time, s.teacher_id as teacher_id, 
  u.name as teacher_name, s.classroom_id as classroom_id, 
  c.name as classroom_name
FROM sections s
JOIN grades g ON s.grade_id = g.id
JOIN periods p ON s.period_id = p.id
LEFT JOIN teachers t ON s.teacher_id = t.id -- allows nulls for s.teacher_id
LEFT JOIN users u ON t.user_id = u.id -- allows nulls on t.user_id
LEFT JOIN classrooms c ON s.classroom_id = c.id -- allows nulls for s.classroom_id

这样,您将使用 WHERE 子句只包括“筛选条件”,但不再包括“联接条件”。阅读和调试会简单得多。

相关问题