MySQL 限制多对多关系

2022-01-18 00:00:00 database tags mysql tagging

给定一个用于实现标签的 SCHEMA

Given a SCHEMA for implementing tags

项目项目 ID、项目内容

ITEM ItemId, ItemContent

标签标记ID、标记名称

TAG TagId, TagName

ITEM_TAGItemId, TagId

ITEM_TAG ItemId, TagId

使用标签选择时限制返回的ITEMS数量的最佳方法是什么?

What is the best way to limit the number of ITEMS to return when selecting with tags?

SELECT i.ItemContent, t.TagName FROM item i 
INNER JOIN ItemTag it ON i.id = it.ItemId 
INNER JOIN tag t ON t.id = it.TagId 

当然是将它们全部取回的最简单方法,但是使用限制子句会失效,因为您会得到每个标签的所有项目的副本,这计入 LIMIT 中的行数.

is of course the easiest way to get them all back, but using a limit clause breaks down, because you get an duplicate of all the items for each tag, which counts toward the number of rows in LIMIT.

推荐答案

我的第二个解决方案使用 MySQL 函数 GROUP_CONCAT() 将所有匹配项目的标签组合成一个逗号分隔的字符串在结果集中.

My second solution uses a MySQL function GROUP_CONCAT() to combine all tags matching the item into a comma-separated string in the result set.

SELECT i.ItemContent, GROUP_CONCAT(t.TagName ORDER BY t.TagName) AS TagList
FROM item AS i 
  INNER JOIN ItemTag AS it ON i.id = it.ItemId 
  INNER JOIN tag AS t ON t.id = it.TagId
GROUP BY i.ItemId;

GROUP_CONCAT() 函数是 MySQL 的一项功能,它不是标准 SQL 的一部分.

The GROUP_CONCAT() function is a MySQL feature, it's not part of standard SQL.

相关文章