如何获得以逗号分隔的十个值列表而不是全部?

How do I get a comma separated list of ten values and not all of them?

我需要将一组动态行更新为给定值,我想在以下查询中::

UPDATE tbl_names n 
SET n.queue_id = (SELECT MAX(id) FROM tbl_queue ORDER BY 1 DESC)
WHERE n.id IN (SELECT nm.id FROM tbl_names nm ORDER BY 1 DESC LIMIT 10)

但是我使用的 MySQL 版本不允许在子查询中使用 LIMIT:

SHOW VARIABLES LIKE "%version%";

+----------------+--------+
| Variable_name  | Value  |
+----------------+--------+
| innodb_version | 5.7.27 |
| version        | 5.7.27 |
+----------------+--------+

然后我想创建变量并将子查询的结果分配给它们:

SET @queueId = (SELECT MAX(id) FROM tbl_queue q ORDER BY 1 DESC);
SET @nameIds = (SELECT GROUP_CONCAT(n.id) FROM tbl_names n ORDER BY 1 DESC LIMIT 10);

UPDATE cases c SET c.queue_id=@queueId WHERE c.id IN (@nameIds);

但问题是 GROUP_CONCAT 不遵守 LIMIT 并返回 table 的所有 ID。

我从 here 知道以下内容:

One important thing you need to be aware of when using GROUP_CONCAT() is that the result is truncated to the maximum length that is provided by the group_concat_max_len system variable, which has a default value of 1024.

This variable’s value can be set higher, by using the following syntax:

SET [GLOBAL | SESSION] group_concat_max_len = val; Where val is an unsigned integer.

However, note that the effective maximum length of the return value is itself constrained by the value of max_allowed_packet.

但是这样做:

SET SESSION group_concat_max_len = 10;
SET @nameIds = (SELECT GROUP_CONCAT(n.id) FROM tbl_names n ORDER BY 1 DESC);
SELECT @nameIds;

Returns 只有一个 ID,而不是我期望的 10 个。我做错了什么?我想我误解了 group_concat_max_len 是如何工作的。仅获取 10 个 Id 作为逗号分隔值的正确方法是什么?

使用 SUBSTRING_INDEX()10 作为 3d 参数:

SELECT SUBSTRING_INDEX(GROUP_CONCAT(n.id), ',', 10) FROM tbl_names n