我有两个表如下什么是查询显示2表中的内容没有重复的数据?
forum_t (forum_id PK, question,description).
forum_answer (forum_answer_id PK,comment,forum_id).
现在我想通过这两个表合并,以获得问题,说明和(特定forum_id评论这是第一台和第二表的外键的主键结果)。
我有两个表如下什么是查询显示2表中的内容没有重复的数据?
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或任何的langauge您使用客户方爆炸的意见。
参见:http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat
除非你聚集'comment'列,你总是会得到复制'question' /'description'列。你有什么尝试? – 2013-03-18 14:26:45