0
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 中设置条件,以便结果与上面的示例完全相同?

提前致谢

4

3 回答 3

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 ;

SQL 小提琴演示

请注意:您编写JOINs 的方式不正确。ON子句后面没有JOIN子句。您必须将连接条件放在ON子句之后。

于 2012-12-04T11:08:25.853 回答
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
于 2012-12-04T11:02:06.160 回答
0

您可以Left joinorright join代替joinor inner joinLeft 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 
于 2012-12-04T11:02:35.523 回答