MySQL条件不包括一些所需的记录

时间:2013-05-28 19:51:20

标签: mysql

我有5个表格,我想加入MySQL以返回参加课程的学生名单,他们注册的课程,这些课程的作业以及学生在每项作业中获得的成绩(或如果学生尚未完成作业,则为NULL)。

table_students
id, name
1, John
2, Jacob
3, Jingleheimer
4, Schmidt

table_courses
id, name
20, English
30, Math 
40, Science

table_assignments
id, courseid, name
1, 20, English Assignment 1
2, 20, English Assignment 2
3, 20, English Assignment 3
4, 30, Math Assignment 1
5, 30, math Assignment 2
6, 40, Science Assignment 1
7, 40, Science Assignment 2
8, 40, Science Assignment 3
9, 40, Science Assignment 4

table_course_enrollments
studentid, courseid
1, 30
1, 40
3, 30
3, 20
4, 40

table_assignment_grades
studentid, courseid, assignmentid, grade
1, 30, 4, A
1, 40, 6, C
1, 40, 8, B
1, 40, 9, A
3, 30, 4, D

我想回来:

Student Name,Course Name, Assignment Name, Grade
John, Math, Math Assignment 1, A
John, Math, Math Assignment 2, Null
John, Science, Science Assignment 1, C
John, Science, Science Assignment 2, Null
John, Science, Science Assignment 3, B
John, Science, Science Assignment 4, D
Jingleheimer, Math, Math Assignment 1, D
Jingleheimer, Math, Math Assignment 2, Null
Jingleheimer, English, English Assignment 1, Null
Jingleheimer, English, English Assignment 2, Null
Schmidt, Science, Science Assignment 1, Null
Schmidt, Science, Science Assignment 2, Null
Schmidt, Science, Science Assignment 3, Null
Schmidt, Science, Science Assignment 4, Null

(雅各没有数据,因为他没有参加任何课程)

我的查询:

SELECT table_students.name, table_courses.name, table_assignments.name, table_assignment_grades.grade

FROM table_students AS s
JOIN table_course_enrollments AS ce ON ce.userid=s.id
JOIN table_courses AS c ON c.id=ce.courseid
JOIN table_assignments AS a ON a.courseid=c.id
LEFT JOIN table_assignment_grades AS ag ON ag.userid=u.id

WHERE ag.assignmentid=a.id
AND ag.courseid=c.id

结果包括学生和课程的预期,但只有学生完成的成绩和作业,而不是所有作业,已完成或未完成。如果我删除WHERE子句,我会得到所有分配的列表,但是分数和分配彼此不匹配。 assignment_grades表需要加入学生,作业和课程,以便正确报告。

我如何重写这项内容,只返回已注册课程的学生,这些课程的作业以及每项作业的成绩,即使作业未被评分?

非常感谢任何提示! 金伯

2 个答案:

答案 0 :(得分:2)

只需将WHERE中的条件放在最后ON中即可解决问题:

SELECT table_students.name, table_courses.name, table_assignments.name,
       table_assignment_grades.grade
FROM table_students AS s
JOIN table_course_enrollments AS ce ON ce.userid=s.id
JOIN table_courses AS c ON c.id=ce.courseid
JOIN table_assignments AS a ON a.courseid=c.id
LEFT JOIN table_assignment_grades AS ag ON ag.userid=u.id
   AND ag.assignmentid=a.id
   AND ag.courseid=c.id

答案 1 :(得分:0)

您需要将WHERE条件移至左侧加入ON子句,否则您将过滤掉所有没有等级的行,而不是将其设置为NULL你期待;

SELECT s.name sname, c.name cname, a.name aname, ag.grade
FROM table_students AS s
JOIN table_course_enrollments AS ce ON ce.studentid=s.id
JOIN table_courses AS c ON c.id=ce.courseid
JOIN table_assignments AS a ON a.courseid=c.id
LEFT JOIN table_assignment_grades AS ag 
  ON ag.studentid=s.id
 AND ag.assignmentid=a.id
 AND ag.courseid=c.id
ORDER BY s.id,c.id

An SQLfiddle to test with