views:

26

answers:

1

Hi everybody, 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 stores 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 ;-)

+3  A: 

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:

OMG Ponies
Yes, that seems correct, sorry, I was looking at more of a UNION result X-)
astander
THANK YOU VERY VERY MUCH... I cant believe that i didnt find that... I really searched for hours... ending up in recursive methods or whatever... Hoped it would be that simple. Just had to add the GROUP_CONCAT and worked like a charme in seconds... THANK YOU!!!!
Booosh
I only modified it a bit to s.th like GROUP_CONCAT... AS tagsMade it easier to read.. THANK YOU!!!
Booosh
@Booosh: Sorry, yeah - in my haste, I didn't provide a column alias for the `GROUP_CONCAT` column
OMG Ponies