不要随意改 sql_mode | LIXI.FUN
0%

不要随意改 sql_mode

1
2
3
4
5
6
7
8
select
id,
min(create_time),
create_by
from
t_result
group by
id;

初见这条 sql,认为不能运行,create_by 字段既没有在 group by 中,也没有聚合函数作用,怎么就能运行呢?

直到看到了运行的图。。。

在自己机器上试,就不能运行,看报错

1
2
3
4
5
SQL错误[1005]: Expression #3 of SELECT list is not in GROUP BY clause 
and contains nonaggregated column 'create_by' which is not functionally
dependent on columns in GROUP BY clause;

this is incompatible with sql_mode=only_full_group_by

跟推断一致,没有在 GROUP BY 中,也没有聚合函数作用,不能运行。

重点在最后一句 this is incompatible with sql_mode=only_full_group_by,再问之,是不是改了 sql_mode,答,是。

那这个 only_full_group_by 有什么作用,能不能改呢?

可以参考下 stackoverflow - what-are-the-benefits-of-only-full-group-by-mode 里的说法。

开启是一种比较严格的,确定性的模式,比较推荐。

关闭是非严格模式,允许突破上面说的 GROUP BYSELECT 字段的限制,但是某些数据可能有不确定的结果。

那能不能改?

I know what I'm doing 的情况下,可以改。

如果单纯因为自己写的 SQL 报错,百度出来结果让改 sql_mode,那我还是建议再琢磨琢磨自己写的 SQL 。

更多参考

觉得有收获就鼓励下作者吧