在Mysql中我們常常用order by來進(jìn)行排序,使用limit來進(jìn)行分頁,當(dāng)需要先排序后分頁時我們往往使用類似的寫法select * from 表名 order by 排序字段 limt M,N。但是這種寫法卻隱藏著較深的使用陷阱。在排序字段有數(shù)據(jù)重復(fù)的情況下,會很容易出現(xiàn)排序結(jié)果與預(yù)期不一致的問題。
如表:
上面的實際執(zhí)行結(jié)果已經(jīng)證明現(xiàn)實與想像往往是有差距的,實際SQL執(zhí)行時并不是按照上述方式執(zhí)行的。這里其實是Mysql會對Limit做優(yōu)化,具體優(yōu)化方式見官方文檔:https://dev.mysql.com/doc/refman/5.7/en/limit-optimization.html
/*
Navicat MySQL Data Transfer
Source Server : 本地mysql8.0
Source Server Version : 80018
Source Host : localhost:3308
Source Database : baihe
Target Server Type : MYSQL
Target Server Version : 80018
File Encoding : 65001
Date: 2020-06-09 14:47:37
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for purchaseinfo
-- ----------------------------
DROP TABLE IF EXISTS `purchaseinfo`;
CREATE TABLE `purchaseinfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) DEFAULT '0',
`inout` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`money` int(11) DEFAULT NULL,
`actiontime` datetime DEFAULT NULL COMMENT 'jiaoyi',
PRIMARY KEY (`id`),
KEY `UserId` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- ----------------------------
-- Records of purchaseinfo
-- ----------------------------
INSERT INTO `purchaseinfo` VALUES ('7', '1', 'I', '10000', '2020-06-09 18:05:41');
INSERT INTO `purchaseinfo` VALUES ('8', '7788', 'O', '20000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('9', '7788', 'I', '20000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('10', '7788', 'O', '50000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('11', '1', 'O', '50000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('12', '1', 'O', '50000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('13', '1', 'O', '50000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('14', '1', 'O', '50000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('15', '1', 'O', '50000', '2020-06-09 18:05:15');
INSERT INTO `purchaseinfo` VALUES ('16', '1', 'O', '50000', '2020-06-09 18:05:15');
到此這篇關(guān)于詳解Mysql order by與limit混用陷阱的文章就介紹到這了,更多相關(guān)Mysql order by與limit混用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!