mysql - 在 Group Concat 中显示前 X 个结果
问题描述
我有一个查询,它返回所有者拥有的项目列表:
WITH all_items
AS
(
SELECT owner.id AS owner,
item.title,
item.importance
FROM owner
JOIN item
ON item.owner_id = owner.id)
SELECT owner.id,
group_concat(DISTINCT item.title ORDER BY item.importance SEPARATOR ',')
FROM owner
JOIN all_items
ON all_items.owner = owner.id
我需要将 group_concat 限制为最多 6 个项目。我不能在 all_items 中执行 LIMIT,因为它只返回前 6 项,无论所有者是谁。我该怎么做呢?
解决方案
最简单的方法是substring_index()
:
substring_index(group_concat(DISTINCT item.title ORDER BY item.importance SEPARATOR ','), ',', 6)
您的查询缺少 aGROUP BY
并且看起来过于复杂。我不知道你为什么要重新回到owner
桌子上。事实上,你根本不需要加入它。为什么不直接使用这个?
SELECT i.owner_id AS owner,
group_concat(DISTINCT i.title ORDER BY i.importance SEPARATOR ',')
FROM item i
GROUP BY i.owner_id;
您也可以使用不同的方法获得前六个:
SELECT i.owner_id AS owner,
group_concat(DISTINCT i.title ORDER BY i.importance SEPARATOR ',')
FROM (SELECT i.*,
DENSE_RANK() OVER (PARTITION BY i.owner_id ORDER BY i.importance DESC, i.title) as seqnum
FROM item i
) i
WHERE seqnum <= 6
GROUP BY i.owner_id;
这样做的好处是,当所有者拥有数以万计的物品时,您不必担心GROUP_CONCAT()
字符串限制(假设标题不是很长)。
推荐阅读
- database - 如何找出存储过程最后一次在 Oracle 中执行的时间?
- php - Laravel 5.8:动态更改油门余量不起作用
- java - 一些对象成员未推送到 Firebase 实时数据库
- typescript - 如何将对象类型映射到自身的扩展中
- ruby-on-rails - 如何不断重定向到 Rails 中的新页面?
- bazel - 带有 python 包的 CLion 插件
- javascript - How use toggleClass
- javascript - How to return a value from forEach
- python - Pandas:将 timedelta 列舍入到 15 秒
- python - 使用 BERT 的 wordpiece 分词器时如何处理标签