系统环境

Ubuntu16.04+MySQL5.7.27;

问题

将数据从旧的数据库(MySQL5.1)迁移到新的数据库(MySQL5.7)中时,查询语句不变的情况下,报如下错;

  1. Cause: java.sql.SQLException:
  2. Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'mwyq_db.news.news_time'
  3. which is not functionally dependent on columns in GROUP BY clause;
  4. this is incompatible with sql_mode=only_full_group_by

解决方法

查看sql-mode

修改后应该如下图所示,未修改前有ONLY_FULL_GROUP_BY选项;

  1. SELECT @@sql_mode;
  2. SELECT @@GLOBAL.sql_mode;
  3. SELECT @@session.sql_mode;

Group by 查询时遇见 ONLY FULL GROUP BY 错误 - 图1

修改sql-mode

  • 临时修改

root用户进入mysql,然后添加如下配置;

  1. SET @@GLOBAL.sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
  2. SET @@session.sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
  3. SET @@sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
  • 永久修改
  1. vim /etc/mysql/my.cnf
  2. mysqld节点下添加:
  1. sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

注意

MySQL8.0中,不支持NO_AUTO_CREATE_USER,所以在修改配置时,需要将这一项去掉;