2011-02-28 126 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