2010-07-08 64 views
2

我有2個表中的行:加入MySQL中2個表,返回不相關

表1:問題(ID,問題,日期)

表2:答案(ID,question_id,答案,日期)

一個問題可以有1個以上的答案,有些問題沒有答案。我想只輸出懸而未決的問題

SELECT * FROM問題,答案查詢WHERE questions.id!=answers.question_id group by questions.id不起作用

有人能幫助新手喜歡我,我很迷失在這一切MySQL的東西。

回答

1
SELECT id, question, date 
FROM questions q 
WHERE NOT EXISTS 
    (SELECT * FROM answers a 
    WHERE a.question_id = q.id) 

OR

SELECT id, question, date 
FROM questions q 
LEFT JOIN answers a ON a.question_id = q.id 
WHERE a.id IS NULL 

OR

SELECT id, question, date 
FROM questions q 
WHERE q.id NOT IN 
    (SELECT question_id FROM answers WHERE question_id IS NOT NULL) 
           /* If question_id can't be NULL this is not needed*/ 
+0

謝謝。沒想到會這麼快。再次感謝你,它的工作原理。愛MySQL – olegb 2010-07-08 15:49:56

2
SELECT Q.id, Q.question, Q.date 
FROM questions Q LEFT JOIN answers A ON (Q.id = A.question_id) 
WHERE A.id IS NULL 
0

SELECT * FROM 問題,答案 WHERE answers.answer = null或answers.answer = 「」;