GROUP_CONCAT 每1000条分行显示
时间: 2023-07-28 09:14:03 浏览: 88
在使用 GROUP_CONCAT 函数时,如果结果集非常大,可能会导致字符串长度超出 MySQL 默认的 max_allowed_packet 配置值而被截断。为了避免这种情况,可以使用以下方法每1000条分行显示:
```sql
SELECT
GROUP_CONCAT(column_name SEPARATOR ', ')
FROM
table_name
GROUP BY
some_column
INTO @result;
SET SESSION group_concat_max_len = @@max_allowed_packet;
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(@result, ',', n), ',', -1) AS result
FROM
(SELECT
a.N + b.N * 1000 + 1 AS n
FROM
(SELECT
0 AS N
UNION ALL SELECT
1 UNION ALL SELECT
2 UNION ALL SELECT
3 UNION ALL SELECT
4 UNION ALL SELECT
5 UNION ALL SELECT
6 UNION ALL SELECT
7 UNION ALL SELECT
8 UNION ALL SELECT
9) AS a
CROSS JOIN
(SELECT
0 AS N
UNION ALL SELECT
1 UNION ALL SELECT
2 UNION ALL SELECT
3 UNION ALL SELECT
4 UNION ALL SELECT
5 UNION ALL SELECT
6 UNION ALL SELECT
7 UNION ALL SELECT
8 UNION ALL SELECT
9) AS b
ORDER BY
n) AS nums
WHERE
n <= LENGTH(@result) - LENGTH(REPLACE(@result, ',', '')) + 1;
```
这里使用了 MySQL 中的 SESSION 变量来设置 group_concat_max_len 值,以便能够存储较长的结果集。然后,使用 SUBSTRING_INDEX 函数和一个嵌套查询来将结果集分割成1000行。
阅读全文