我有5個表,我想加入到MySQL中,以返回參加課程的學生列表,他們參加的課程,這些課程中的任務以及學生的成績在每個作業中獲得(如果學生尚未完成作業,則爲NULL)。MySQL條件不包括一些所需的記錄
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
結果包括如預期的學生和課程,但只有學生完成的成績和作業,而不是所有作業,c完成與否。如果我刪除WHERE子句,我會得到所有作業的列表,但是成績和作業彼此不匹配。需要將assignment_grades表連接到學生,作業和課程才能正確報告。
如何重寫這個表格,僅返回參加課程的學生,這些課程中的作業,以及每個作業的成績,即使作業尚未評分?
非常感謝任何提示! 伯
感謝您的詳細回覆! –