相信作为DBA 在和开发打交道的过程中,经常会遇到分页查询 order by 排序这样的需求。本文源于生产过程中的案例,5.6版本的数据库使用limit和order by 一个非唯一字段时,结果集并不总是确定的.已经确定为bug,详见:MySQL 官方的bug
提醒读者朋友注意。
二 分析
环境准备
-
CREATE TABLE `tb1` (
-
`id` bigint(20) NOT NULL AUTO_INCREMENT,
-
`a` decimal(19,2) NOT NULL,
-
`acid` bigint(20) NOT NULL,
-
`prid` bigint(20) NOT NULL,
-
PRIMARY KEY (`id`),
-
KEY `idx_prid` (`prid`),
-
KEY `idx_acid` (`acid`)
- ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8
初始化数据
-
INSERT INTO `tb1` (`id`, `a`, `acid`, `prid`)
- VALUES (1,2.00,3,2),(2,3.00,3,2),(3,4.00,2,3),(4,5.00,2,3),(5,6.00,2,3),(6,8.00,2,3),(7,10.00,2,3),(8,12.00,2,3),(9,16.00,2,3),(10,20.00,2,3),(11,6.00,2,4),(12,8.00,2,4),(13,10.00,2,4),(14,12.00,2,4),(15,5.00,2,2),(16,6.00,2,2);
-
MysqL> select * from tb1 order by a desc limit 4;
-
+----+-------+------+------+
-
| id | a | acid | prid |
-
+----+-------+------+------+
-
| 10 | 20.00 | 2 | 3 |
-
| 9 | 16.00 | 2 | 3 |
-
| 14 | 12.00 | 2 | 4 |
-
| 8 | 12.00 | 2 | 3 |
-
+----+-------+------+------+
- 4 rows in set (0.00 sec)
-
MysqL> select * from tb1 order by a desc limit 3;
-
+----+-------+------+------+
-
| id | a | acid | prid |
-
+----+-------+------+------+
-
| 10 | 20.00 | 2 | 3 |
- | 9 | 16.00 | 2 | 3 |
-
| 8 | 12.00 | 2 | 3 |
-
+----+-------+------+------+
- 3 rows in set (0.00 sec)
为a字段加上索引
-
MysqL> alter table tb1 add key ind_tb1a(a);
-
Query OK, 0 rows affected (0.00 sec)
-
Records: 0 Duplicates: 0 Warnings: 0
-
MysqL> select * from tb1 order by a desc limit 3;
-
+----+-------+------+------+
-
| id | a | acid | prid |
-
+----+-------+------+------+
-
| 10 | 20.00 | 2 | 3 |
-
| 9 | 16.00 | 2 | 3 |
-
| 8 | 12.00 | 2 | 3 |
-
+----+-------+------+------+
- 3 rows in set (0.00 sec)
-
MysqL> select * from tb1 order by a desc limit 4;
-
+----+-------+------+------+
-
| id | a | acid | prid |
-
+----+-------+------+------+
-
| 10 | 20.00 | 2 | 3 |
-
| 9 | 16.00 | 2 | 3 |
-
| 14 | 12.00 | 2 | 4 |
-
| 8 | 12.00 | 2 | 3 |
-
+----+-------+------+------+
- 4 rows in set (0.00 sec)
从上面的测试来看对于一个非唯一字段 无论是否含有索引,结果集都是不确定的。
三 解决方法
1 业务属性确保 a 字段不能唯一,则需要针对排序结果再加上 一个唯一字段的排序 比如id
-
MysqL> select * from tb1 order by a desc ,id desc limit 4;
-
+----+-------+------+------+
-
| id | a | acid | prid |
-
+----+-------+------+------+
-
| 10 | 20.00 | 2 | 3 |
-
| 9 | 16.00 | 2 | 3 |
-
| 14 | 12.00 | 2 | 4 |
-
| 8 | 12.00 | 2 | 3 |
-
+----+-------+------+------+
- 4 rows in set (0.00 sec)
-
MysqL> select * from tb1 order by a desc ,id desc limit 3;
-
+----+-------+------+------+
-
| id | a | acid | prid |
-
+----+-------+------+------+
-
| 10 | 20.00 | 2 | 3 |
-
| 9 | 16.00 | 2 | 3 |
-
| 14 | 12.00 | 2 | 4 |
-
+----+-------+------+------+
- 3 rows in set (0.00 sec)
2 是否可以去掉不必要的order by,这个是由业务逻辑决定的。
四 总结
DBA在和开发沟通/培训过程中要注意这一点 基于非唯一字段的排序 结果集是不确定的。如果业务逻辑对分页或者order by结果集有比较高的严格要求 ,请记得利用唯一键排序。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。