首页 > 解决方案 > 在 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 项,无论所有者是谁。我该怎么做呢?

标签: mysqllimitgroup-concat

解决方案


最简单的方法是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()字符串限制(假设标题不是很长)。


推荐阅读