Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL one-to-many join with Group By only returns one observation

Tags:

join

mysql

I have a comment table and a tag table. For each comment, there could be multiple tags, or none. I want to join the two so I can get a list of tags for each comment.

CommentTable:

+---------+----------+---+
|CommentID|   Title  | ..|
+---------+----------+---+
|   1     |   animals|   |
|   2     |   plants |   |
+---------+----------+---+

TagTable:

+---------+----------+---+
|  TagID  |CommentID | ..|
+---------+----------+---+
|    5    |     1    |   |
|    6    |     1    |   |
|    7    |     3    |   |
+---------+----------+---+

So, a query should return the tags, (5,6) for a commentID == 1 and empty array for CommentID == 2

This is what I have - it only selects the last ID and not multiples:

SELECT c.CommentID, c.Title,  t.TagID  FROM Comment as c
        LEFT OUTER JOIN Tag as t ON c.CommentID = t.CommentID
        GROUP BY t.TagID
like image 543
Justin Avatar asked Aug 04 '12 09:08

Justin


2 Answers

You can use GROUP_CONCAT to turn data in multiple rows into a single delimited string:

SELECT    a.CommentID, 
          a.Title,
          GROUP_CONCAT(b.TagID ORDER BY b.TagID) AS tags
FROM      CommentTable a
LEFT JOIN TagTable b ON a.CommentID = b.CommentID
GROUP BY  a.CommentID,
          a.Title

In this case, if a comment does not have a corresponding tag, the field would just be NULL.


SQLFiddle Demo

like image 153
Zane Bien Avatar answered Sep 19 '22 01:09

Zane Bien


try this:

SELECT c.CommentID, c.Title,  t.TagID  FROM Comment as c
        LEFT OUTER JOIN Tag as t ON c.CommentID = t.CommentID

edit1: If you want to return only one row per group as per the comment

SELECT c.CommentID, c.Title,MAX(t.TagID )
FROM Comment as c
left OUTER JOIN TagTable as t ON c.CommentID = t.CommentID
GROUP BY  c.CommentID, c.Title
like image 32
Joe G Joseph Avatar answered Sep 21 '22 01:09

Joe G Joseph