MySQL 限制多对多关系 [英] MySQL Limit with Many to Many Relationship

查看:71
本文介绍了MySQL 限制多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个用于实现标签的 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.

这篇关于MySQL 限制多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆