mysql5.7 先排序ORDER BY,后分组 GROUP BY

关于mysql5.7  排序ORDER BY ,分组 GROUP BY

 

安装最新的MySQL5.7,发现之前group by语句报错,发现mysql5.7 默认开启 only_full_group_by 模式,

错误信息如下:

[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'user.order_no' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

解决方式:

第一种方式:直接修改配置文件删掉only_full_group_by

第二种方式:

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'

上面sql改变全局sql_mode,新建的数据库有效

 

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';

这条sql修改已存在的数据库sql_mode

 

然后开始执行先排序后分组的sql

SELECT * FROM
(SELECT * FROM users ORDER BY user_id DESC) temp
GROUP BY temp. user_id

发现排序居然没有生效,顿时很惊讶

explain 查看执行计划,发现在没有 limit 的情况,会少了一个derived 操作,mysql会认为这时候不需要排序,内部做了优化,所以这种情况下加limit限制就可以了,如下(limt 后的行数 可以作为参数传入):

SELECT * FROM
(SELECT * FROM users ORDER BY user_id DESC limit 100) temp
GROUP BY temp. user_id

 

你可能感兴趣的:(数据库)