Expression #1 of ORDER BY clause is not in SELECT list, references column 'nav_db.map.order_index...

在做业务查询列表时候出现问题,捕获的异常如下

SQL state [HY000]; error code [3065]; Expression #1 of ORDER BY clause is not in SELECT list, references column 'nav_db.map.order_index' which is not in SELECT list; this is incompatible with DISTINCT; nested exception is java.sql.SQLException: Expression #1 of ORDER BY clause is not in SELECT list, references column 'nav_db.map.order_index' which is not in SELECT list; this is incompatible with DISTINCT

在程序中运行时会报错,但是使用naticat却执行成功。

通过查阅资料发现在mysql5.7.5及以上版本实现了对功能依赖的检测。默认启用了ONLY_FULL_GROUP_BY SQL模式。在该模式下,

  1. 使用GROUP BY查询时,出现在SELECT字段后面的只能是GROUP BY后面的分组字段,或使用聚合函数包裹着的字段,否则会报错如下信息:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database.table.column' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
  2. 当使用ORDER BY查询时,不能使用SELECT DISTINCT去重查询。否则会报错如下信息:Expression #1 of ORDER BY clause is not in SELECT list, references column 'database.table.column' which is not in SELECT list; this is incompatible with DISTINCT

解决方法

  1. 通过命令关闭ONLY_FULL_GROUP_BY SQL模式
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';
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';
  1. 通过修改mysql的配置文件关闭ONLY_FULL_GROUP_BY SQL模式
[mysqld]
sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

你可能感兴趣的:(Expression #1 of ORDER BY clause is not in SELECT list, references column 'nav_db.map.order_index...)