0

我有 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

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

我的查询:

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 表需要连接到学生、作业和课程才能正确报告。

我如何重写它以仅返回已注册课程的学生、这些课程中的作业以及每个作业的成绩,即使作业尚未评分?

非常感谢任何提示!金伯

4

2 回答 2

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
于 2013-05-28T20:00:57.880 回答
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

一个用于测试的 SQLfiddle

于 2013-05-28T20:03:59.227 回答