SELECT subjects.name as name , grades.grade as grade, concat(instructors.lastname, ", ", instructors.firstname , " ", left(instructors.middlename, 1),".") as instructor
FROM subjects
JOIN grades
JOIN instructors
WHERE grades.student_id = 1 AND subjects.id = grades.subject_id AND instructors.subject_id = subjects.id
结果是
English Instructor Grade
Math Instructor Grade
但我想要的是在没有教师的科目中给予“N / A”。实施例
English Instructor Grade
Math Instructor Grade
Science N/A Grade
History N/A Grade
我将如何在mySQL中设置条件,以便结果看起来完全符合上述示例?
提前致谢
答案 0 :(得分:1)
LEFT JOIN
代替INNER JOIN
,如此:
SELECT
s.name as name ,
g.grade as grade,
IFNULL(concat(i.lastname, ", ", i.firstname, ...), 'N/A') as instructor
FROM subjects s
LEFT JOIN grades g ON g.subject_id = s.id
LEFT JOIN instructors i ON g.subject_id = i.subject_id ;
请注意:您编写JOIN
的方式不正确。 ON
子句后面没有JOIN
子句。您必须将连接条件放在ON
子句之后。
答案 1 :(得分:0)
试试这个::
使用左连接和ifnull
SELECT subjects.name as name , grades.grade as grade, ifnull(concat(instructors.lastname, ", ", instructors.firstname , " ", left(instructors.middlename, 1),"."),'N/A)' as instructor
FROM subjects
LEFT JOIN grades on subjects.id = grades.subject_id
LEFT JOIN instructors on instructors.subject_id = subjects.id
WHERE grades.student_id = 1
答案 2 :(得分:0)
您可以Left join
或right join
代替join
或inner join
。如果没有相关数据,Left Join
将显示左侧的所有数据,右侧显示null。所以你的查询将成为:
SELECT subjects.name as name , grades.grade as grade,
isnull(concat(instructors.lastname, ", ", instructors.firstname , " ",
left(instructors.middlename, 1),"."), 'N/A') as instructor
FROM subjects
LEFT JOIN grades ON subjects.id = grades.subject_id
LEFT JOIN instructors ON instructors.subject_id = subjects.id
WHERE grades.student_id = 1