我有两个表如下
forum_t (forum_id PK, question,description).
forum_answer (forum_answer_id PK,comment,forum_id).
现在我想要通过组合这两个表来获取特定 forum_id 的问题、描述和评论的结果(这是第一个表中的主键和第二个表中的外键)。
SELECT question,description,comment
FROM
forum_t
INNER JOIN
forum_answer
ON forum_t.forum_id=forum_answer.forum_id
WHERE
forum_t.forum_id={your forum id}
要删除重复项,请使用DISTINCT
关键字,但每个问题您不会得到一条记录,因为您可能有很多答案和评论。
SELECT DISTINCT F.forum_id,F.question,F.description,A.comment
FROM forum_t F INNER JOIN forum_answer A on F.forum_id = A.forum_id
WHERE F.forum_id = 1
如果您真的想每个问题得到一行,那么您将不得不使用某种聚合函数。
首先是计数(每个问题的答案数)。
select q.forum_id, q.question, q.description, count(*) as answer_count
from forum_t q
inner join forum_answer a on (q.forum_id = a.forum_id)
where q.forum_id between 1 and 10 -- first 10 questions
group by q.forum_id
如果你想要实际的答案,你可以使用 group_concat 然后放在一起
select
q.forum_id
, q.question
, q.description
, count(*) as answer_count
, group_concat(a.comment) as comments_in_csv_form
from forum_t q
inner join forum_answer a on (q.forum_id = a.forum_id)
where q.forum_id between 1 and 10 -- first 10 questions
group by q.forum_id
您现在可以使用 php 或您在客户端使用的任何语言来展开评论。
请参阅:http ://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat