2013-05-01 63 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