服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - MySQL子查询中order by不生效问题的解决方法

MySQL子查询中order by不生效问题的解决方法

2021-09-03 21:40simpleapples Mysql

ORDER BY 语句用于根据指定的列对结果集进行排序,在日常工作中经常会用到,这篇文章主要给大家介绍了关于MySQL子查询中order by不生效问题的解决方法,需要的朋友可以参考下

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

问题描述

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

MySQL子查询中order by不生效问题的解决方法

MySQL子查询中order by不生效问题的解决方法

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

?
1
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;

通过结果可以看到,子查询先将product_operation_log_tbl里的所有记录按创建时间(created_at)逆序,然后和product_tbl进行join操作,进而查询出的商品的最新修改时间。

MySQL子查询中order by不生效问题的解决方法

在区域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子查询中order by不生效问题的解决方法

可以看到,只有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中这种写法依然是生效的

到此这篇关于mysql子查询中order by不生效问题的文章就介绍到这了,更多相关mysql子查询order by不生效内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

参考文档

https://stackoverflow.com/questions/26372511/mysql-mariadb-order-by-inside-subquery

https://mariadb.com/kb/en/why-is-order-by-in-a-from-subquery-ignored/

原文链接:https://zhuanlan.zhihu.com/p/394446365

延伸 · 阅读

精彩推荐