MySQL与Group By的一对多连接仅返回一个观察

时间:2012-08-04 09:59:26

标签: mysql join

我有一个评论表和一个标签表。对于每个评论,可能有多个标签,或者没有。我想加入这两个,所以我可以得到每个评论的标签列表。

CommentTable:

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

TagTable:

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

因此,查询应返回标记,(5,6)为commentID == 1,空数组为CommentID == 2

这就是我所拥有的 - 它只选择最后一个ID而不是倍数:

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

3 个答案:

答案 0 :(得分:28)

您可以使用GROUP_CONCAT将多行数据转换为单个分隔字符串:

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

在这种情况下,如果注释没有相应的标记,则该字段将只为NULL。


SQLFiddle Demo

答案 1 :(得分:1)

试试这个:

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

edit1:如果你想根据评论

每组只返回一行
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

答案 2 :(得分:-1)

在这种情况下你不需要小组:

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