开发者

MySQL problem: Merging multiple results/rows caused by n-m

i tried now nearly everything i could to solve he following problem. So far with no success. But there must be a solution cause i dont think the case is s.th too special. I think i am just a bloody beginner ;-) I need to join union merge or whatever ;-) in MySQL to solve the following problem...

CASE: Three tables "posts", "tagmap" and "tags"

The tagmap table stores all n-m relations the id's of the posts and the id's of the tags

The tags table sto开发者_运维问答res the tag_name with the tag id

The posts table stores the post_title and the post_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 => Chalk

post_id => 1, post_title => Charlie Chaplin... tag_name => Poster

Does anyone know how this could be achieved... Any help would be highly appreciated and thx in advance to everyone who could help me out whith this ;-)


Use:

  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

Reference:

  • GROUP_CONCAT
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜