当前位置:首页 > 数据库

深入浅出MySQL优先队列(你一定会踩到的order by limit 问题)

 0.先抛问题

假设字段category无索引且有重复值,深入order by category 和 limit 组合使用的浅出结果会和预期不符。

深入浅出MySQL优先队列(你一定会踩到的order by limit 问题)

问题复现:

深入浅出MySQL优先队列(你一定会踩到的order by limit 问题)

表结构(就是先队两个字段) 

深入浅出MySQL优先队列(你一定会踩到的order by limit 问题)

CREATE TABLE `ratings` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `category` int(11) DEFAULT NULL,    PRIMARY KEY (`id`)  ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 

对所有数据按category字段排序: select * from ratings order by category;

id category 1 1 5 1 10 1 3 2 4 2 6 2 9 2 2 3 7 3 8 3

当我们想分页展示前5条时使用select * from ratings order by category limit 5;

期望得到的ID顺序是1 5 10 3 4。

但实际结果如下:

id category 1 1 10 1 5 1 3 2 4 2

怎么肥似?列定MySQL 出 Bug 了?

可能有同学遇到过这个问题,百度或谷歌一下解决了,问题你有没有想过,深入你查到的浅出办法是最优解吗?别人是怎么得出这个办法的?MySQL 为什么会这样做,跟版本有关吗?先队

先抛结论:

 最优解是后面再加个列值唯一的排序字段,亿华云如:order by category,列定id;  MySQL 为什么这样做?答案是为了快!(MySQL 5.6及其之后才有此优化)  次优解是问题对order by后面的category 加索引(为什么是次优解?看完本文你将会有答案);

下面课代表将还原一下这 3 条结论的产出过程。

1. 最优解

MySQL 文档 8.2.1.19 LIMIT Query Optimization 中对此场景有如下描述:

If multiple rows have 深入identical values in the ORDER BY columns, the server is free to return those rows in any order, and may do so differently depending on the overall execution plan. In other words, the sort order of those rows is nondeterministic with respect to the nonordered columns.

One factor that affects the execution plan is LIMIT, so an ORDER BY query with and without LIMIT may return rows in different orders.

总结来说就是:

当 ORDER BY 列的字段值存在重复,那么这条 ORDER BY 语句返回的浅出数据顺序会因为LIMIT的存在而变得不一样

这是 MySQL 默认对该场景做的优化,如果你需要保证加不加 LIMIT 顺序都要一致,先队官方也给出了办法:

If it is 列定important to ensure the same row order with and without LIMIT, include additional columns in the ORDER BY clause to make the order deterministic.

就是服务器托管在ORDER BY 后面再多加一个排序字段(比如 ID 字段)。

以上描述最早出现在MySQL 5.6文档中,问题从这个版本开始,引入了这个针对ORDER BY LIMIT 的优化。

好了, 针对文中的场景,我们只需要select * from ratings order by category,id;即可解决。

那么问题来了,MySQL 为什么要做这么一个看似是 Bug 的优化?

2.MySQL 的 ORDER BY 逻辑

顾名思义,ORDER BY 就是排序。

执行一下explain select * from ratings order by category limit 5;

站群服务器

分享到:

滇ICP备2023006006号-16