如何加入这些表格?

时间:2011-10-22 16:26:43

标签: php mysql sql

我有三张桌子:

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
----------------------------------------------

现在,我想用用户(提问者)的姓名,姓氏,用户名和问题总答案数来检索所有问题。

请帮忙写一下。因为我搞砸了我的查询,所以没有在这里发布。

谢谢

2 个答案:

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

答案 1 :(得分:-1)

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