Select 来自 MySQL table 的所有行与不存在的关系作为空单元格
Select all rows from MySQL table with non-existent relation as empty cell
例如,如果我有两个 table 分别称为 'teachers' 和 'lessons',并且 'lessons' 有一个外键 'teacher_ID' 引用它在'teachers' table,那么我如何 select all 行来自老师的 all 对应的课程如果没有课程与它们相关联,则用一个空单元格?我只能让 MySQL 向我展示 有 一节或多节课的老师。
如果没有 LEFT JOIN,这甚至可能吗?我在 Google...
上找不到任何内容
编辑
我对 LEFT JOIN 关键字的机制很感兴趣。但是由于似乎没有其他选择,我会说 case closed.
正确的方法是使用LEFT JOIN
。这样,如果不匹配,您将得到 (teacher_id), null
The LEFT JOIN keyword returns all the rows from the left table (teachers), even if there are no matches in the right table (lessons).
SELECT teacher.teacher_ID, lesson.lesson_ID
FROM teachers
LEFT JOIN lessons
ON teacher.teacher_ID = lesson.teacher_ID
如果你想模仿LEFT JOIN
首先使用JOIN
来找到匹配的元素。并使用 UNION
添加其余值为 NULL
SELECT teacher.teacher_ID, lessons.lesson_ID
FROM teachers
JOIN lessons
ON teacher.teacher_ID = lessons.teacher_ID
UNION
SELECT teacher.teacher_ID, null as lesson_ID
FROM teachers
WHERE NOT EXISTS ( SELECT 1
FROM lessons
WHERE lessons.teacher_id = teacher.teacher_id)
例如,如果我有两个 table 分别称为 'teachers' 和 'lessons',并且 'lessons' 有一个外键 'teacher_ID' 引用它在'teachers' table,那么我如何 select all 行来自老师的 all 对应的课程如果没有课程与它们相关联,则用一个空单元格?我只能让 MySQL 向我展示 有 一节或多节课的老师。
如果没有 LEFT JOIN,这甚至可能吗?我在 Google...
上找不到任何内容编辑 我对 LEFT JOIN 关键字的机制很感兴趣。但是由于似乎没有其他选择,我会说 case closed.
正确的方法是使用LEFT JOIN
。这样,如果不匹配,您将得到 (teacher_id), null
The LEFT JOIN keyword returns all the rows from the left table (teachers), even if there are no matches in the right table (lessons).
SELECT teacher.teacher_ID, lesson.lesson_ID
FROM teachers
LEFT JOIN lessons
ON teacher.teacher_ID = lesson.teacher_ID
如果你想模仿LEFT JOIN
首先使用JOIN
来找到匹配的元素。并使用 UNION
添加其余值为 NULL
SELECT teacher.teacher_ID, lessons.lesson_ID
FROM teachers
JOIN lessons
ON teacher.teacher_ID = lessons.teacher_ID
UNION
SELECT teacher.teacher_ID, null as lesson_ID
FROM teachers
WHERE NOT EXISTS ( SELECT 1
FROM lessons
WHERE lessons.teacher_id = teacher.teacher_id)