首页 > 解决方案 > 排序字段的数据重复时MySql如何对数据进行排序?

问题描述

当排序字段的数据重复时,MySql如何对数据进行排序?

桌子:

CREATE TABLE `orderby_test` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `sort1` bigint(20) NOT NULL,
  `sort2` bigint(20) NOT NULL,
  `a` bigint(20) NOT NULL ,
  `b` bigint(20) NOT NULL ,
  PRIMARY KEY (`id`),
  KEY `idx_sort` (`sort1`, `sort2`)
) ENGINE=InnoDB AUTO_INCREMENT=1;

sql:

select id, sort1,sort2,a,b from  orderby_test where sort1 = 1 and a = 1 and b = 1 order by sort2 desc limit 0, 1000

然后插入数据3次:

    insert into orderby_test (sort1,sort2,a,b) values (1,3,1,1);

然后选择,结果是:

id  sort1   sort2   a   b
1   1   3   1   1
2   1   3   1   1
3   1   3   1   1

id 是 ASC

然后插入数据 20 次:

    insert into orderby_test (sort1,sort2,a,b) values (1,3,1,1);

然后选择,结果是:

id  sort1   sort2   a   b
12  1   3   1   1
23  1   3   1   1
22  1   3   1   1
21  1   3   1   1
20  1   3   1   1
19  1   3   1   1
18  1   3   1   1
17  1   3   1   1
16  1   3   1   1
15  1   3   1   1
14  1   3   1   1
13  1   3   1   1
1   1   3   1   1
11  1   3   1   1
10  1   3   1   1
9   1   3   1   1
8   1   3   1   1
7   1   3   1   1
6   1   3   1   1
5   1   3   1   1
4   1   3   1   1
3   1   3   1   1
2   1   3   1   1

id没有排序!</h2>

为什么?


如果你做更多插入

结果 :

select id, sort1,sort2,a,b from  orderby_test where sort1 = 1 and a = 1 and b = 1 order by sort2 desc limit 0, 20
id  sort1   sort2   a   b
282 1   3   1   1
281 1   3   1   1
280 1   3   1   1
279 1   3   1   1
278 1   3   1   1
277 1   3   1   1
276 1   3   1   1
275 1   3   1   1
274 1   3   1   1
273 1   3   1   1
272 1   3   1   1
271 1   3   1   1
270 1   3   1   1
269 1   3   1   1
268 1   3   1   1
267 1   3   1   1
266 1   3   1   1
265 1   3   1   1
259 1   3   1   1
258 1   3   1   1

id又被排序了!</h2>

因为innodb中B+树的实现?mysql是怎么做到的?

mysql 版本:5.7.21-21-log

标签: mysql

解决方案


排序字段的数据重复时MySql如何对数据进行排序?

它没有。

一旦 MySQL 有足够的信息以符合ORDER BY子句的方式排列结果集,它就会尽可能快地打包带有关系的行,而不关心它的相对顺序。

这不是 MySQL 特有的,它是 SQL 设计的行为方式。排序有成本(时间、CPU、内存……);当不需要排序时,支付这样的费用是没有意义的。


推荐阅读