MySQL order by 排序結(jié)果不正確
創(chuàng)新互聯(lián)專注于惠安網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供惠安營銷型網(wǎng)站建設(shè),惠安網(wǎng)站制作、惠安網(wǎng)頁設(shè)計(jì)、惠安網(wǎng)站官網(wǎng)定制、小程序開發(fā)服務(wù),打造惠安網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供惠安網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
新建一張測試表:
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;
字段 a 沒有索引,插入測試數(shù)據(jù):
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);
查看表數(shù)據(jù):
([yoon]> select * from tb1;
+----+-------+------+------+
| id | a | acid | prid |
+----+-------+------+------+
| 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 |
+----+-------+------+------+
根據(jù)非索引字段且有重復(fù)數(shù)據(jù)的字段 a 進(jìn)行 order by 排序:
([yoon]> select * from tb1 order by a desc ;
+----+-------+------+------+
| id | a | acid | prid |
+----+-------+------+------+
| 10 | 20.00 | 2 | 3 |
| 9 | 16.00 | 2 | 3 |
| 14 | 12.00 | 2 | 4 |
| 8 | 12.00 | 2 | 3 |
| 13 | 10.00 | 2 | 4 |
| 7 | 10.00 | 2 | 3 |
| 12 | 8.00 | 2 | 4 |
| 6 | 8.00 | 2 | 3 |
| 11 | 6.00 | 2 | 4 |
| 16 | 6.00 | 2 | 2 |
| 5 | 6.00 | 2 | 3 |
| 4 | 5.00 | 2 | 3 |
| 15 | 5.00 | 2 | 2 |
| 3 | 4.00 | 2 | 3 |
| 2 | 3.00 | 3 | 2 |
| 1 | 2.00 | 3 | 2 |
+----+-------+------+------+
order by 和 limit 一起使用:
([yoon]> 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 |
+----+-------+------+------+
為 a 字段添加索引:
([yoon]> alter table tb1 add index idx_a(a);
Query OK, 0 rows affected (0.05 sec)
([yoon]> 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 |
+----+-------+------+------+
排序的時候再添加一個字段 id :
([yoon]> 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 |
+----+-------+------+------+
對于一個非唯一字段,無論是否含有索引,結(jié)果集都是不確定的。如果業(yè)務(wù)邏輯對分頁或者order by結(jié)果集有比較高的嚴(yán)格要求 ,請記得利用唯一鍵排序。