Mysql – get all posts with their associative tags without duplicates

join;many-to-manyMySQL

Two tables. Post and Tag. Many to Many bi-directional relationship.

Post Table              Tag Table             Post_Tag Pivot Table
---------------         ------------          -----------------
id   content            id   name             id_post   id_tag
---------------         ------------          -----------------
 1   hey there           1    php                1        1
                         2    python             1        2

I want to get all posts with their tags.

I've tried this:

SELECT P.title, T.tag
From Post P
JOIN Tag T
ORDER BY P.id DESC

It works, but it gives duplicates:

hey there, php
hey there, python

Is there a way to group tags together in one row here. Thanks

Best Answer

You didn't provide DDL and sample data so we can't test anything. Also, it is not clear what is the join predicate, but I think you are looking for GROUP_CONCAT, something along the lines of (Pseudo code):

SELECT P.Title, GROUP_CONCAT(T.Tag SEPARATOR ',') AS Concatenated_Tags
FROM Post P INNER JOIN Tag T ...
GROUP BY P.Title;

HTH