2011-02-28 128 views
1

我有一个简单的查询疑问。选择没有答案的问题

Question Table 
qid question 
1 ques1 
2 ques2 
3 ques3 
4 ques4 
5 ques5 
6 ques6 
7 ques7 

Answer Table 
ansid qid answer 
1  1 ans1 
2  2 ans2 
3  2 ans3 
4  4 ans4 
5  6 ans5 

我有两个表。一个用于提问,另一个用于答案。问题ID(QID)在回答表中用作外键。我想要选择在答案表中没有答案的问题。在上面的例子中,我需要问题3,5,7。我的数据库很大,可能包含超过50,000条记录。

感谢 阿伦

+0

请邮寄到现在为止您编写的代码。人们通常不喜欢只为你写代码。事实上,这是一个工作描述,而不是一个问题。 – 2011-02-28 10:47:58

+0

你可能需要一个OUTER JOIN http://en.wikipedia.org/wiki/Join_%28SQL%29 – 2011-02-28 10:50:42

回答

3
select q.* from question as q 
left join answer as a 
on q.id = a.qid 
where a.qid is null 

编辑。 此外,它会更好,在回答表添加一个索引

alter table answer add index iq (qid); 
1
select * from question where qid not in 
(select qid from answer) 
+0

现在我正在使用这个查询。它给了我正确的答案。如果我使用这个,是否有任何性能问题。 SELECT question FROM tbl_question q LEFT JOIN tbl_answer a ON q.id = a.qid WHERE a.qid IS NULL – 2011-02-28 10:52:52

+0

不在mysql中很慢并且可以避免。 – 2011-02-28 10:54:11

+0

@ user504383 - 猜测这是子查询vs连接的经典案例。就你而言,我相信性能差异可以忽略不计。 – 2011-02-28 10:55:06