首页 文章

MySQL问题:合并由n-m引起的多个结果/行

提问于
浏览
0

我现在几乎尝试了所有可以解决问题的方法 . 到目前为止没有成功 . 但必须有一个解决方案因为我不认为案件太特别了 . 我想我只是一个血腥的初学者;-)我需要加入union merge或者其他;-)在MySQL中解决以下问题......

案例:三个表“帖子”,“标签图”和“标签”

tagmap 表存储标签的id 's of the posts and the id'的所有n-m关系
tags 表将 tag_nametag id存储在一起
posts 表存储 post_titlepost_id

posts    post_id    post_title
          1          Charlie Chaplin Painting

 tagmap   id         post_id    tag_id
          100        1          12
          101        1          13
          102        1          14

 tags     tag_id     tag_name
          12         Acryl
          13         Chalk
          14         Poster

What i am trying to achieve is to get a result as the follwing where all related tags are merged in one column. Either by a comma separated list or spaces:
post_id => 1,post_title => Charlie Chaplin ... tag_name => Acryl,Chalk,Poster

But till now the only thing i could get are mukltiple results like this:
post_id => 1,post_title => Charlie Chaplin ... tag_name => Acryl
post_id => 1,post_title => Charlie Chaplin ... tag_name =>粉笔
post_id => 1,post_title => Charlie Chaplin ... tag_name =>海报

有谁知道如何实现这一点......任何帮助都会受到高度赞赏,并提前给所有可以帮助我解决这个问题的人;-)

1 回答

  • 2

    使用:

    SELECT p.post_id,
             p.post_title,
             GROUP_CONCAT(t.tag_name ORDER BY t.tag_name SEPARATOR ', ')
        FROM POSTS p
        JOIN TAGMAP tm ON tm.post_id = p.post_id
        JOIN TAGS t ON t.tag_id = tm.tag_id
    GROUP BY p.post_id, p.post_title
    

    参考:

相关问题