14

我有一个评论表和一个标签表。对于每条评论,可能有多个标签,也可能没有。我想加入这两者,这样我就可以获得每个评论的标签列表。

评论表:

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

标签表:

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

因此,查询应该返回标签,(5,6) 用于评论 ID == 1 和空数组用于评论 ID == 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
4

3 回答 3

33

您可以使用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 演示

于 2012-08-04T10:44:07.457 回答
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
于 2012-08-04T10:03:05.367 回答
-1

对于这种情况,您不需要 group by:

SELECT c.CommentID, c.Title,  t.TagID  FROM Comment as c
LEFT OUTER JOIN Tag as t ON c.CommentID = t.CommentID
于 2012-08-04T10:03:58.273 回答