2015-10-05 35 views
0

當我談到MySQL時,我仍然在學習,我試圖將問題與它的答案組合在一起(就像你會在學校進行測試一樣)。下面是我和我的查詢得到的結果:來自LEFT_JOIN的意外結果。 (返回空值)

enter image description here

預期的結果是底部的4行,所有的數據是可用的。這個(對我來說)更令人困惑的部分是,我的任何列中的值都不是NULL,所以我不明白爲什麼它會被返回。

LEFT_JOIN不是正確的方法來執行此?如果不是,那是什麼?很感謝鏈接到詳細的文檔。

這裏是我當前的查詢:

SELECT 
    Q.question_id, 
    Q.question, 
    Q.account_id, 
    A.answer, 
    A.correct 
FROM quiz_answers A LEFT JOIN quiz_questions Q ON 
    A.question_id = Q.question_id 
    AND A.account_id = Q.account_id 
    AND A.account_id = 48 
    AND Q.account_id = 48 

ORDER BY Q.question_id; 

查詢仍返回不符合條件的行,但與NULL,而不是數據填充的結果。查詢的預期結果是上面提供的圖像中的底部4行。

+1

將'AND A.account_id = 48 AND Q.account_id = 48'移到where條件而不是連接子句。 –

+1

http://blog.codinghorror。com/a-visual-explanation-of-sql-joins/ –

+0

@AbhikChakraborty這就是我想要的,謝謝。似乎它會產生相同的結果,只是閱讀它。 – Hobbyist

回答

1

至於說通過abhik

SELECT 
Q.question_id, 
Q.question, 
Q.account_id, 
A.answer, 
A.correct FROM quiz_answers A LEFT JOIN quiz_questions Q ON 
A.question_id = Q.question_id 
where A.account_id = Q.account_id 
AND A.account_id = 48 ORDER BY Q.question_id 
+0

如果A.account_id = Q.account_id你不需要檢查他們都是48 – Alfons

+0

對不起,我沒有注意到 –

0

您首先要加入2個表格,然後您想要刪除(使用where)您不想看到的條目。在這種情況下,它最好使用內連接:

SELECT 
    Q.question_id, 
    Q.question, 
    Q.account_id, 
    A.answer, 
    A.correct 
FROM quiz_answers A INNER JOIN quiz_questions Q ON 
    A.question_id = Q.question_id 
    AND A.account_id = Q.account_id 
Where 
    A.account_id = 48 
ORDER BY Q.question_id; 
0

這是左連接的正確行爲。它將顯示連接中左表中的所有條目,如果右表沒有對應的值,則會添加null。

您可以使用左連接來列出您的數據庫中的所有問題,並顯示那些有答案或沒有答案。要做到這一點,你必須寫:

FROM quiz_questions LEFT JOIN quiz_answers 

如果你只是想擁有的那些有答案的問題的結果,你應該做的

FROM quiz_questions JOIN quiz_answers 

,將只顯示那些ID是在這兩個表格。

而且你應該寫你的情況是這樣的:

FROM quiz_questions A JOIN quiz_answers Q ON 
    A.question_id = Q.question_id 
WHERE Q.account_id = 48 

得到wour期望的結果。