mysql8 执行SQL语句报错 "this is incompatible with sql_mode=only_full_group_by"

一、原理层面

       这个错误发生在mysql 5.7 版本及以上版本会出现的问题:

       mysql 5.7版本默认的sql配置是:sql_mode="ONLY_FULL_GROUP_BY",这个配置严格执行了"SQL92标准"。

       很多从5.6升级到5.7时,为了语法兼容,大部分都会选择调整sql_mode,使其保持跟5.6一致,为了尽量兼容程序。

        

 二、sql层面

        在sql执行时,出现该原因:

        简单来说就是:输出的结果是叫target list,就是select后面跟着的字段,还有一个地方group by column,就是

        group by后面跟着的字段。由于开启了ONLY_FULL_GROUP_BY的设置,所以如果一个字段没有在target list 

        和group by字段中同时出现,或者是聚合函数的值的话,那么这条sql查询是被mysql认为非法的,会报错误。

原因分析:MySQL版本默认设置了 mysql sql_mode = only_full_group_by 属性,导致报错。

解决方案

C:UsersLenovo>mysql -u root -p
Enter password: ******
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 12
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

mysql> SELECT @@sql_mode;
+-----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                            |
+-----------------------------------------------------------------------------------------------------------------------+
| ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

修改sql_mode:

#修改全局 于新建的数据库有效。
mysql> SET @@global.sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)
 
 
#修改当前设置 对于已存在的数据库,则需要在对应的数据下执行:
mysql> SET sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)
每天学习一点点,你就进步一点点。
原文地址:https://www.cnblogs.com/zhangliang88/p/14377386.html