mysql |来自两个表的条​​件查询

时间:2014-10-06 06:20:32

标签: php mysql sql

我有两张桌子:

问题

id title
1  First question
2  Second question
3  Third question

答案

id   text    question_id
1    Answer1 1
2    Answer2 1
3    Answer3 2

我正在搜索查询以返回未回答的问题(问题ID:上例中的3)? 谢谢!

5 个答案:

答案 0 :(得分:2)

Select id, title from question A Left Join answer B on A.id=B.question_id where B.question_id  is null

答案 1 :(得分:1)

由于Mysql不支持MINUS(或者至少我不知道)你必须使用join

SELECT q.id
FROM questions q LEFT JOIN answers a
ON q.id = a.question_id
WHERE a.question_id is null

答案 2 :(得分:0)

select id,title from questions where id NOT IN(select distinct(question_id) from answers)

NOT in in mysql会帮助你

答案 3 :(得分:0)

试试这个:

select * from questions left outer join answers on questions.id = question_id
where question_id is null

答案 4 :(得分:0)

select q.id,q.title from questions q where q.id NOT IN(select distinct(question_id) from answers)

未使用安全查询以查找已回答的问题。