我有以下查询
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
外键可能为空。但是,如果这些外键中的任何一个为空,mysql将从所有相关表中排除整个列。
我该如何更改查询,以便mysql将显示 sections 表中的数据,即使这些键为空。
答案 0 :(得分:3)
您需要使用外部联接。
首先,您需要使用自1992年以来可用的现代JOIN语法。使用此语法,您可以使用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
子句仅包括“过滤条件”,而不再包括“联接条件”。阅读和调试起来会容易得多。