一个偶然的机会,发现一条SQL语句在不同的MySQL实例上执行得到了不同的结果。

问题描述

创建商品表product_tbl和商品操作记录表product_operation_tbl两个表,来模拟下业务场景,结构和数据如下:

接下来需要查询所有商品最新的修改时间,使用如下语句:

select t1.id, t1.name, t2.product_id, t2.created_at  from product_tbl t1 left join (select * from product_operation_log_tbl order by created_at desc) t2 on t1.id = t2.product_id group by t1.id;


在区域A的MySQL实例上,查询商品最新修改时间可以得到正确结果,但是在区域B的MySQL实例上,得到的修改时间并不是最新的,而是最老的。通过对语句进行简化,发现是子查询中的order by created_at desc语句在区域B的实例上没有生效。

排查过程

难道区域会影响MySQL的行为?经过DBA排查,区域A的MySQL是5.6版,区域B的MySQL是5.7版,并且找到了这篇文章:

https://blog.csdn.net/weixin_42121058/article/details/113588551

根据文章的描述,MySQL 5.7版会忽略掉子查询中的order by语句,可令人疑惑的是,我们模拟业务场景的MySQL是8.0版,并没有出现这个问题。使用docker分别启动MySQL 5.6、5.7、8.0三个实例,来重复上面的操作,结果如下:


可以看到,只有MySQL 5.7版忽略了子查询中的order by。有没有可能是5.7引入了bug,后续版本又修复了呢?

问题根因

继续搜索文档和资料,发现官方论坛中有这样一段描述:

A "table" (and subquery in the FROM clause too) is - according to the SQL standard - an unordered set of rows. Rows in a table (or in a subquery in the FROM clause) do not come in any specific order. That's why the optimizer can ignore the ORDER BY clause that you have specified. In fact, SQL standard does not even allow the ORDER BY clause to appear in this subquery (we allow it, because ORDER BY ... LIMIT ... changes the result, the set of rows, not only their order). You need to treat the subquery in the FROM clause, as a set of rows in some unspecified and undefined order, and put the ORDER BY on the top-level SELECT.

问题的原因清晰了,原来SQL标准中,table的定义是一个未排序的数据集合,而一个SQL子查询是一个临时的table,根据这个定义,子查询中的order by会被忽略。同时,官方回复也给出了解决方案:将子查询的order by移动到最外层的select语句中。

总结

在SQL标准中,子查询中的order by是不生效的

MySQL 5.7由于在这个点上遵循了SQL标准导致问题暴露,而在MySQL 5.6/8.0中这种写法依然是生效的

更多相关文章

  1. Linux下MYSQL 5.7 找回root密码的问题(亲测可用)
  2. Android(安卓)10 定位问题,获取NMEA(支持5.0~10.0)
  3. mybatisplus的坑 insert标签insert into select无参数问题的解决
  4. 关于Android(安卓)Studio3.2新建项目Android(安卓)resource link
  5. Android软键盘适配问题
  6. SlidingMenu和ActionBarSherlock结合做出出色的App布局,Facebook
  7. android解决坚屏拍照和保存图片旋转90度的问题,并兼容4.0
  8. Android(安卓)Calendar使用过程中遇到的问题
  9. flutter-使用第三方库,编译和运行版本不一致问题 2

随机推荐

  1. VSCode跳转到定义内部实现_VSCode插件开
  2. ES2018
  3. TypescriptServerPlugin_VSCode插件开发
  4. Taro
  5. Android(安卓)源码导入Eclipse技巧(Ubuntu
  6. Android(安卓)调用摄像头功能【拍照与视
  7. 选中菜单android中的显示跳转和隐式跳转
  8. SimpleCropView 裁剪图片
  9. Android(安卓)实现联网(四)——TCP/UDP
  10. 面试官:能给我说说sleep和wait的区别嘛?