【问题标题】:getting rows from a MySQL database associated with tags through a link table通过链接表从与标签关联的 MySQL 数据库中获取行
【发布时间】:2012-12-15 01:39:24
【问题描述】:

我有三个 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 |
+----+------------+------------+--------+-------------+

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

【问题讨论】:

  • 请考虑接受您提出的一些问题的答案。点击最佳答案旁边的绿色复选框。
  • 我对每个回答我的问题的答案都这样做......在我在这里写一个问题之前我做了很多搜索......我正在尽我所能帮助这个伟大的社区可以;-)

标签: mysql search tags


【解决方案1】:

您需要将GROUP BYgroup_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

【讨论】:

  • 如果您发现自己在查询中使用 SELECT *MAX()GROUP_CONCAT() 等聚合函数,您可能做错了。你肯定在做一些草率且不便携的事情。
  • 这确实为给定表提供了所需的结果。我遇到了另一个问题,添加了一个没有标签的链接,它也应该在结果中返回,但没有标签。我将“加入”更改为“左加入”,这就解决了这个问题! (这里小提琴:sqlfiddle.com/#!2/5b772/2/0
猜你喜欢
  • 2018-08-19
  • 2019-01-11
  • 1970-01-01
  • 2011-02-02
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
相关资源
最近更新 更多