2011-10-22 32 views
0

我有三個表:如何加入這些表格?

users 
----------------------------------- 
id | firstname | lastname | username 
----------------------------------- 
1 | John  | Doe  | jdoe 
----------------------------------- 
2 | Maria | T.  | marty 
----------------------------------- 
3 | Alex  | White | alexw 
----------------------------------- 

questions 
-------------------------------------------- 
id | user_id | title 
-------------------------------------------- 
1 | 2  | My first question? 
-------------------------------------------- 
2 | 3  | One more question? 
-------------------------------------------- 
3 | 3  | The third question? 
-------------------------------------------- 

answers 
---------------------------------------------- 
id | question_id | description 
---------------------------------------------- 
1 | 2   | Answers to the 2nd question 
---------------------------------------------- 
2 | 1   | Answer for 1st question 
---------------------------------------------- 
3 | 1   | Another answer for 1st 
---------------------------------------------- 

現在,我想檢索與用戶(提問者)名字,姓氏,用戶名和問題給出答案,總的計數所有問題。

請幫忙寫一下。由於我已經搞亂了我的查詢,請不要在這裏發佈。

感謝

+0

你爲什麼要使用用戶ID時,你可以擁有用戶名作爲主鍵? –

+0

你不是指爲*問題*提供的全部答案的數量嗎? – vol7ron

+1

@AurelioDeRosa:只是因爲有一個'id'字段,它並不能成爲主鍵,但通常情況下總是有好處。想象一下,如果你將表格結構化爲有效日期,你可以擁有相同的'用戶名'(主鍵可以是*用戶名* + *日期字段*),但是記錄'id'仍然是唯一的。 – vol7ron

回答

3
SELECT q.*, u.*, COUNT(a.id) as answer_count 
FROM questions q 
LEFT JOIN users u ON q.user_id = u.id 
LEFT JOIN answers a ON a.question_id = q.id 
GROUP BY q.id 
+0

很確定你需要一個組在那裏 – vol7ron

+0

@ vol7ron是的,錯過了。 – xdazz

+0

它的工作原理。非常感謝! 我錯過了「group by」。 – aryan

-1
select users.fistname,users.lastname,users.username 
from users, questions, answers 
where users.id = questions.user_id and questions.id = answers.question_id 
+0

這個需求可能不是100%清楚,但是我我猜測所有問題都必須列出,即使沒有用戶回答他們。在這個基礎上,我認爲你需要一些左連接,就像@xdazz一樣。 – halfer

+0

所有問題都必須列出,但您的查詢會給出多餘的問題。 是的,即使沒有用戶回答它。 – aryan