[英]mySQL SELECT using LEFT JOIN, returning value or NULL WHERE column is specified in right table
我是一名剛接觸php | mySQL的高中老師,我正在嘗試開發一個查詢來顯示我的學生的考試成績。 挑戰是在給定測試中顯示分數,如果尚未發布分數則顯示NULL。 我想在單個查詢中執行兩個步驟:
帶有每個評估記錄的“測試”表包含以下列:
test_id
assessment_id
username
score
maxScore
stopTime
包含每個學生記錄的“用戶”表包含以下列:
user_id
schoolId
username
first_name
last_name
section
期望的結果:
username | last_name | first_name | schoolId | assessment_id | score | maxScore
------------------------------------------------------------------------------------
jadams1 | Adams | Joe | 111111 | 23 | 9 | 12
sbenson1 | Benson | Sally | 222222 | 23 | 10 | 12
csmith2 | Smith | Charlie | 555555 | NULL | NULL | NULL (hasn't taken quiz yet)
dthomp1 | Thompson | David | 666666 | 23 | 9 | 12
到目前為止,我已經嘗試了很多東西。 第一個是基本的LEFT JOIN。 這會為每個學生生成一行,但由於我為“tests.assessment_id”指定了一個值,因此它不會為尚未參加測驗的學生顯示行。 我希望它顯示測驗結果(如果存在),如果學生沒有參加測驗則顯示包含NULL分數值的行。
SELECT
users.last_name,
users.first_name,
tests.score,
tests.maxScore
FROM users
LEFT JOIN tests
ON tests.username = users.username
WHERE tests.assessment_id = '23'
AND users.section = 'S432-01'
以上產生:
username | last_name | first_name | schoolId | assessment_id | score | maxScore
------------------------------------------------------------------------------
jadams1 | Adams | Joe | 111111 | 23 | 9 | 12
sbenson1 | Benson | Sally | 222222 | 23 | 10 | 12
dthomp1 | Thompson | David | 666666 | 23 | 9 | 12
以下是最近的迭代。 它為練習測驗生成一個NULL行(沒有分配assessment_id)以及真實的一行。 在最終報告中,為每個學生只創建一行非常重要,但不要錯過任何學生:
SELECT DISTINCT
users.username,
users.last_name,
users.first_name,
users.schoolId,
if(tests.assessment_id ='23','23','') AS assessment,
if(tests.assessment_id ='23',tests.score,'') AS score,
if(tests.assessment_id ='23',tests.maxScore,'') AS maxScore
FROM `users`
LEFT JOIN tests
ON tests.username = users.username
WHERE users.section = 'S432-01'
AND (tests.assessment_id = '23'
OR tests.assessment_id IS NULL)
ORDER BY users.last_name,users.first_name,tests.assessment_id
以上產生:
username | last_name | first_name | schoolId | assessment_id | score | maxScore
------------------------------------------------------------------------------------
jadams1 | Adams | Joe | 111111 | NULL | NULL | NULL
jadams1 | Adams | Joe | 111111 | 23 | 9 | 12
sbenson1 | Benson | Sally | 222222 | NULL | NULL | NULL
sbenson1 | Benson | Sally | 222222 | 23 | 10 | 12
csmith2 | Smith | Charlie | 555555 | NULL | NULL. | NULL (hasn't taken quiz yet)
dthomp1 | Thompson | David | 666666 | NULL | NULL. | NULL
dthomp1 | Thompson | David | 666666 | 23 | 9 | 12
任何想法如何在單個查詢中使這個工作? 我認為我遇到了性能問題,所以我希望盡可能保持簡單。
謝謝你的幫助! -克里斯
這會工作,
SELECT users.last_name,
users.first_name,
tests.score,
tests.maxScore
FROM users
LEFT JOIN tests
ON tests.username = users.username AND
tests.assessment_id = '23'
WHERE users.section = 'S432-01'
您沒有從users
表中獲取所有記錄的原因是因為您已過濾了等於23
assessment_id
,其中刪除了所有null
值( 未評估的學生在此列上具有空值 )。 要獲取所有值,請在ON
子句上移動tests.assessment_id='23'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.