0

我有三个 MySQL 表,一个带有数据,一个带有标签,一个带有这两者之间的关联,这似乎是存储标签时的常见做法。表格如下所示:

links:
+----+------------+------------+
| id | url        | added      |
+----+------------+------------+
| 2  | google.com | 2012-12-14 |
| 3  | cnn.com    | 2001-02-13 |
+----+------------+------------+

tags:    
+----+--------+
| id | tag    |
+----+--------+
| 1  | search |
| 2  | news   |
+----+--------+


taglink:
+----+--------+-------+
| id | linkid | tagid |
+----+--------+-------+
| 1  | 2      | 1     |
| 2  | 3      | 1     |
| 3  | 3      | 2     |
+----+--------+-------+

我想收到的是下表:

+----+------------+------------+--------+-------------+
| id | url        | added      | tagids | tags        |
+----+------------+------------+--------+-------------+
| 2  | google.com | 2012-12-14 | 1      | search      |
| 3  | cnn.com    | 2001-02-13 | 1,2    | search,news |
+----+------------+------------+--------+-------------+

为此,我有以下查询:

select 
   links.*,
   group_concat(taglink.id) as tagids,
   group_concat(tags.tag) as tags
from links
   join taglink on taglink.linkid=links.id
   join tags on tags.id=taglink.tagid

但这给了我一个使用每个标签的单行,如下所示:

+----+------------+------------+--------+-------------+
| id | url        | addad      | tagids | tags        |
+----+------------+------------+--------+-------------+
| 2  | google.com | 2012-12-14 | 1,2    | search,news |
+----+------------+------------+--------+-------------+

一切似乎都是分组的,这不是我想要的。有人知道解决方案吗?

4

1 回答 1

2

您需要按如下方式使用GROUP BY您的函数,否则它们的行为将无法预测。group_concat尝试这个。

    select links.id, links.url, links.added,
           group_concat(tags.id ORDER BY tags.id) as tagids,
           group_concat(tags.tag ORDER BY tags.id) as tags
      from links
      join taglink on taglink.linkid=links.id
      join tags on tags.id=taglink.tagid
  group by links.id, links.url, links.added
  order by links.id

请注意,我添加了一些ORDER BY项目以使事物的顺序可预测。

去小提琴: http ://sqlfiddle.com/#!2/2b3b9/5/0

于 2012-12-15T01:49:27.893 回答