1
  • post (id_post, title)
  • tag (id_tag, name)
  • post_tag (id_post_tag, id_post, id_tag)

Lets suppose that id_post 3 has 4 linked tags 1,2,3,4 (soccer, basket, tennis and golf).

Is there a way to return something like this in ONE row?

  • col 1 id_post = 3
  • col 2 tags = soccer basket tennis golf

Thanks

1 Answer 1

2

Use:

  SELECT p.id_post
         GROUP_CONCAT(DISTINCT t.name SEPARATOR ' ')
    FROM POST p
    JOIN POST_TAG pt ON pt.id_post = p.id_post
    JOIN TAG t ON t.id_tag = pt.id_post_tag
GROUP BY p.id_post

Be aware that the default separator is a comma, so you have to define a single space if you don't want that between the tag names.

Documentation:

Sign up to request clarification or add additional context in comments.

2 Comments

worked great! just one more doubt... how do i limit the amount of tags, for example: 3 -- i tried to use a LIMIT approach but it won't work.
@andufo: You have to use a variable to provide analytical functionality because it doesn't natively exist in MySQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.