2013-05-01 24 views
0

我有3个MySQL表:MYSQL GROUP_CONCAT多个ID和名称(在多个帖子行多个注释行)

帖子

post_id  post_name  post_date 

    1  Hello   2013-04-23 
    2  Goodbye  2013-04-24 

用户

user_id user_name 

    1  Danny 
    2  Max 

评论

comment_id user_id  post_id  comment_text  comment_date 

    1   1    1  Really good  2013-04-23 
    2   2    2  Really bad  2013-04-24 
    3   2    2  Just joking  2013-04-24 

我的目标是显示多行后,有多个评论(已CON-catted与USER_ID,USER_NAME & COMMENT_TEXT &带分隔符分隔)。

事情是这样的:

结果

Post id  Post name Comments 

    1  Hello  1,Danny,Really good 
    1  Goodbye  2,Max,Really bad|2,Max,Just joking 

我一直在抓我的头几个小时这样的例子的搜索。任何帮助与MYSQL查询将不胜感激!谢谢。

回答

2

可以GROUP_CONCAT内使用CONCAT

事情是这样的: -

SELECT a.post_id, a.post_name, GROUP_CONCAT(CONCAT_WS(",", c.user_id, c.user_name, b.comment_text) SEPARATOR "|") 
FROM Posts a 
INNER JOIN Comments b ON a.post_id = b.post_id 
INNER JOIN Users c ON b.user_id = c.user_id 
GROUP BY a.post_id, a.post_name 
+0

我非常感谢先生 – Danny 2013-05-01 15:51:26