使用MAX函数获取表中某个字段最大值的查询优化
业务场景是获取表中fid的最大值做增量同步,使用以下语句查询,导致阿里云RDS云数据库CPU占用100%
SELECT MAX(`fid`) AS tp_max FROM `hp_erp_barcode` WHERE `hp_erp_barcode`.`delete_time` IS NULL
表结构
/******************************************/
/* DatabaseName = xietong */
/* TableName = hp_erp_barcode */
/******************************************/
CREATE TABLE `hp_erp_barcode` (
`id` int(32) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
`fid` int(32) unsigned NOT NULL DEFAULT '0' COMMENT '条码主档 BD_BarCodeMainFile 实体主键',
`material_id` int(32) unsigned NOT NULL DEFAULT '0' COMMENT '物料id',
`material_number` varchar(64) DEFAULT '' COMMENT '物料编码',
`material_name` varchar(128) DEFAULT '' COMMENT '物料名称',
`barcode` varchar(64) DEFAULT '' COMMENT '条形码',
`forbid_status` varchar(32) DEFAULT '' COMMENT '禁用状态',
`remark` text COMMENT '备注',
`stock_id` int(32) unsigned NOT NULL DEFAULT '0' COMMENT '仓库id',
`stock_number` varchar(64) DEFAULT '' COMMENT '仓库编码',
`stock_name` varchar(64) DEFAULT '' COMMENT '仓库名称',
`bill_code` varchar(64) DEFAULT '' COMMENT '单据编号',
`add_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '添加时间',
`update_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '修改时间',
`delete_time` int(11) unsigned DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
KEY `barcode` (`barcode`),
KEY `bill_code` (`bill_code`),
KEY `idx_fid` (`fid`) USING BTREE,
KEY `idx_delete_time` (`delete_time`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2769985 DEFAULT CHARSET=utf8mb4 COMMENT='ERP条码主档'
;
从表结构可看到,fid
与delete_time
字段都有建立索引,用explain
分析
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
1 | SIMPLE | hp_erp_barcode | ref | idx_delete_time | idx_delete_time | 5 | const | 1165839 | 100 | Using index condition |
表中有两百多万行数据,根据上面的结果,大致找到所需记录需要读取的行数为1165839
,虽然有索引,但效果不理想,分析之后,发现可以通过order by fid desc limit 1
的方式获取fid的最大值
SELECT fid FROM `hp_erp_barcode` WHERE `delete_time` IS NULL ORDER BY `fid` DESC limit 1
使用explain
分析
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
1 | SIMPLE | hp_erp_barcode | index | idx_delete_time | idx_fid | 4 | 2 | 50.00 | Using where |
找到所需记录需要读取的行数为2
,大大提高了搜索的效率。