Mysql ONLY_FULL_GROUP_BY模式详解、group by非查询字段报错

文章目录
  • 一、问题报错
  • 二、ONLY_FULL_GROUP_BY模式
    • 2.1、什么是ONLY_FULL_GROUP_BY?
    • 2.2、为什么要使用ONLY_FULL_GROUP_BY?
    • 2.3、查看sql_mode
  • 三、解决方法
    • 3.1、关闭only_full_group_by模式
      • 3.1.1、方法一:关闭当前会话中的only_full_group_by
      • 3.1.2、方法二:永久关闭only_full_group_by模式
    • 3.2、使用ANY_VALUE()函数
  • 四、其他
    • 4.1、无权限报错
    • 4.2、select后面的字段必须在group by后面出现?当group by遇上唯一索引或主键

以下内容基于Mysql8.0进行讲解ONLY_FULL_GROUP_BY模式。

一、问题报错

Mysql5.7版本以上对group by 分组有了新需求,要求group by 后的字段要与select后查询的字段一致,否则就会报错,报错信息如下:

[2024-09-29 10:48:54] [42000][1055] Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘test.tbl_test.name’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

测试用例如下:

create table tbl_test(
	id int primary key auto_increment,
	name varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci unique not null,
	age int comment '年龄',
	address varchar(50) comment '住址',
	update_t

你可能感兴趣的:(面试,学习路线,阿里巴巴,mysql,数据库)