2011-11-04 53 views
2

我需要做一個查詢來獲得每個學生的特定考試的結果,我也想顯示爲NULL的學生誰沒有進入他的分數....Mysql加入四個表並顯示空值

這裏是我的四個表

  1. Student
  2. Scores
  3. Student
  4. student_subject

enter image description dsds

enter image description here

enter image description here

enter image description here

我的錶鏈接

  • 評分表(USER_ID )與學生表(USER_ID)
  • 考試表(ID)與積分榜(exam.id)
  • student_subject(USER_ID)與學生表(USER_ID)

  • student_subject(GROUP_ID)與考試表( GROUP_ID)(我的組數據庫是在另一個數據庫的一些重要原因)

我查詢的工作,但我沒有爲學生沒有進入他的得分誰NULL值

SELECT 
    scores.result, students.id, exam.name, exam.id 
FROM 
    scores 
LEFT JOIN 
    students ON scores.user_id = students.user_id 
LEFT JOIN 
    exam ON exam.id = scores.exam_id 
LEFT JOIN 
    students_subjects as ss ON ss.user_id = students.id 
LEFT JOIN 
    students_subjects ON students_subjects.group_id = exam.group_id 
WHERE 
    exam.id = 32 
GROUP BY 
    scores.id 

輸出

enter image description here

我怎樣才能爲每個學生沒有得分爲特定的考試,誰空值(exam.id = 32)?

編輯的@sceaj

我與你得到這個是查詢(我改變WHERE exam.id = 34 WHERE exam.id = 36爲更好的測試)

SELECT scores.result,students.id,exam.name, exam.id 
FROM exam 
INNER JOIN students_subjects ON students_subjects.group_id = exam.group_id 
INNER JOIN students ON students_subjects.user_id = students.user_id 
LEFT OUTER JOIN scores ON scores.user_id = students.user_id 
WHERE exam.id = 36 

enter image description here

+0

請分享考試表格結構。 – sceaj

回答

2

以下應返回所有的學生,如果他們存在與考試32分數。

SELECT scores.result,students.id,exam.name, exam.id 
FROM exam 
INNER JOIN scores ON exam.id = scores.exam_id 
RIGHT OUTER JOIN students ON scores.user_id = students.user_id 
WHERE exam.id = 32 

您的select子句沒有使用任何來自students_subjects或聚合函數的東西,所以我不確定它的連接是什麼?也許你可以從上面開始並從那裏開始構建。

編輯:基於我的第一條評論的新戰略。嘗試找到所有學生,然後找到存在的分數,如果沒有,則爲空。

SELECT scores.result,students.id,exam.name, exam.id 
FROM exam 
INNER JOIN students_subjects ON students_subjects.group_id = exam.group_id 
INNER JOIN students ON students_subjects.user_id = students.user_id 
LEFT OUTER JOIN scores ON scores.user_id = students.user_id 
    AND scores.exam_id = exam.id 
WHERE exam.id = 32 
+0

啊,我想我明白了。你想限制輸出的學生應該採取exam.id = 32,但你的students_subject結構和考試的關係是不清楚 – sceaj

+0

因爲我想讓所有學生(例如:group_id = 32),並且你qu​​erry不顯示NULL字段,所以students_subjects與該字段的考試(students_subjects.group_id with exam.group_id)相關聯, thx for you awser –

+0

上面的查詢應該爲整個學生表中的每行返回1行。你介意發佈你得到的結果嗎? – sceaj

0

不要以分數表開始,將所有其他分數連接在一起:只會得到分數不爲零的行。相反,做一個正確的加入,或把分數表結束:

SELECT scores.result,students.id,exam.name, exam.id 
FROM 
students LEFT JOIN scores ON scores.user_id = students.user_id 
LEFT JOIN exam on exam.id = scores.exam_id 
LEFT JOIN students_subjects as ss ON ss.user_id = students.id 
LEFT JOIN students_subjects ON students_subjects.group_id = exam.group_id 
where exam.id = 32 
group by scores.id 
+0

我得到了相同的結果oupout比我的例子:(但thx –