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

前端 未结 3 1214
眼角桃花
眼角桃花 2021-01-02 03:05

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.

<
相关标签:
3条回答
  • 2021-01-02 03:24

    You don't need the group by for this situation:

    SELECT c.CommentID, c.Title,  t.TagID  FROM Comment as c
    LEFT OUTER JOIN Tag as t ON c.CommentID = t.CommentID
    
    0 讨论(0)
  • 2021-01-02 03:50

    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

    0 讨论(0)
  • 2021-01-02 03:51

    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
    
    0 讨论(0)
提交回复
热议问题