在Mysql中我们常常用order by来进行排序,使用limit来进行分页,当需要先排序后分页时我们往往使用类似的写法select * from 表名 order by 排序字段 limt M,N。但是这种写法却隐藏着较深的使用陷阱。在排序字段有数据重复的情况下,会很容易出现排序结果与预期不一致的问题。
如表:
查询第一页跟最后一页时出现:
解决办法:
SELECT * FROM purchaseinfo
ORDER BY actiontime,id LIMIT 0,2;
上面的实际执行结果已经证明现实与想像往往是有差距的,实际SQL执行时并不是按照上述方式执行的。这里其实是Mysql会对Limit做优化,具体优化方式见官方文档: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');