让我们假设两个表:
STUDENTS:
id | name | faculty_id
和
FACULTIES:
id | name
我正在尝试按students.id
查询学生,并将faculties.name
返回students.faculty_id = faculties.id
。
我用过:
SELECT students.*, faculties.name FROM students
JOIN faculties on students.faculty_id = faculties.id
WHERE students.id = ' ... ';
这很有效,但是有一个问题:
如果由于某种错误,该学生被分配了一个不存在的faculty_id
而不是他永远找不到的faculty.name
。我想写更多'灵活的'只有在找到匹配时才返回{{1}}的查询,否则只留空。
此外,查询必须没有内存密集型循环,因为您可以按名称等进行查询...这会导致大量匹配。
答案 0 :(得分:2)
左连接将返回符合您标准的所有学生,无论student.faculty_id是否与有效的faculty.id相关联... ifnull将值设置为空白而不是&#34; null&#34; < / p>
SELECT
students.*,
ifnull(faculties.name,'')
FROM
students
LEFT JOIN faculties on students.faculty_id = faculties.id
WHERE students.id = ' ... ';
答案 1 :(得分:-3)
而不是在您的查询中加入。尝试INNER JOIN
SELECT students.*, faculties.name FROM students
INNER JOIN faculties on students.faculty_id = faculties.id
WHERE students.id = ' ... ';