在mysql中加入2个表,返回不相关的行

时间:2010-07-08 15:40:31

标签: php mysql join

我有两张桌子:

表1:问题(身份证,问题,日期)

表2:答案(id,question_id,answer,date)

一个问题可以有1个以上的答案,有些问题没有答案。我想只输出未回答的问题

SELECT * FROM个问题,答案WHERE questions.id!=answers.question_id group by questions.id之类的查询不起作用

有人可以像我一样帮助新手,我迷失在所有这些mysql中。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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*/

答案 2 :(得分:0)

SELECT * FROM 问题和答案 WHERE answers.answer = null或answers.answer =“”;