半夜被慢查询告警吵醒,竟是limit深度分页的坑……
故事
剖析流程
limit分页为什么会变慢?
CREATE TABLE `Product` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,`type` tinyint(3) unsigned NOT NULL DEFAULT '1' ,`spuCode` varchar(50) NOT NULL DEFAULT '' ,`spuName` varchar(100) NOT NULL DEFAULT '' ,`spuTitle` varchar(300) NOT NULL DEFAULT '' ,`channelId` bigint(20) unsigned NOT NULL DEFAULT '0',`sellerId` bigint(20) unsigned NOT NULL DEFAULT '0'`mallSpuCode` varchar(32) NOT NULL DEFAULT '',`originCategoryId` bigint(20) unsigned NOT NULL DEFAULT '0' ,`originCategoryName` varchar(50) NOT NULL DEFAULT '' ,`marketPrice` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',`status` tinyint(3) unsigned NOT NULL DEFAULT '1' ,`isDeleted` tinyint(3) unsigned NOT NULL DEFAULT '0',`timeCreated` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),`timeModified` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) ,PRIMARY KEY (`id`) USING BTREE,UNIQUE KEY `uk_spuCode` (`spuCode`,`channelId`,`sellerId`),KEY `idx_timeCreated` (`timeCreated`),KEY `idx_spuName` (`spuName`),KEY `idx_channelId_originCategory` (`channelId`,`originCategoryId`,`originCategoryName`) USING BTREE,KEY `idx_sellerId` (`sellerId`)) ENGINE=InnoDB AUTO_INCREMENT=12553120 DEFAULT CHARSET=utf8mb4 COMMENT='商品表'
select * from Product where timeCreated > "2020-09-12 13:34:20" limit 0,10select * from Product where timeCreated > "2020-09-12 13:34:20" limit 10000000,10剖析一下原因
替换limit分页的一些方案
select * FROM Product where id >= (select p.id from Product p where p.timeCreated > "2020-09-12 13:34:20" limit 10000000, 1) LIMIT 10;select * from Product p1 inner join (select p.id from Product p where p.timeCreated > "2020-09-12 13:34:20" limit 10000000,10) as p2 on p1.id = p2.idselect * from Product p where p.timeCreated > "2020-09-12 13:34:20" and id>10000000 limit 10select * from Product p where p.timeCreated > "2020-09-12 13:34:20" and id between 10000000 and 10000010 写到最后
select * from InventorySku isk inner join (select id from InventorySku where inventoryId = 6058 limit 109500,500 ) as d on isk.id = d.id