mysql 查询结果被 截断 问题 group_concat

前几天在项目中遇到一个问题,使用 GROUP_CONCAT 函数select出来的数据被截断了,最长长度不超过1024字节,开始还以为是客户端自身对字段长度做了限制的问题。后来查找出原因

1 查找原因

至此,只能从SQL语句出发了。网上搜了下 GROUP_CONCAT 数据截断的问题,答案都指向了 group_concat_max_len 这个参数,它的默认值正好是1024。可以直接在数据库中通过下面的命令查看这个默认值:

mysql> show variables like 'group_concat_max_len';
Variable_name  | Value |
-|group_concat_max_len | 1024 |

MySQL官方手册 对它的定义是 The maximum permitted result length in bytes for the GROUP_CONCAT() function. ,也就是它限制了 GROUP_CONCAT 数据的长度。

如果是生产环境下,不能擅自重启MySQL服务,则可以通过语句设置group_concat的作用范围,如:

 SET GLOBAL group_concat_max_len=2048;

 SET SESSION group_concat_max_len=2048;

MySQL sql_mode=only_full_group_by 错误

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'blog.categories.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

MySQL 有时会遇到这种问题,后来网上查了一下据库版本为 5.7 以上的版本,默认是开启了 only_full_group_by 模式的,但开启这个模式后,原先的 group by 语句就报错。

原因:

其中 ONLY_FULL_GROUP_BY 就是造成这个错误的原因,

对于 group by 聚合操作,如果在 select 中的列没有在 group by 中出现,那么这个 SQL 是不合法的,因为列不在 group by 从句中,所以设置了 sql_mode=only_full_group_by 的数据库,在使用 group by 时就会报错。