忽然收到RDS服务器cpu 100%的报警,查看后发现有慢查询。取了其中一条:服务器
select * from `kmd_tb_goods` where (`item_id` = 41928087111) and `kmd_tb_goods`.`deleted_at` is null limit 1
我手动执行了一下上面的语句,发现耗时:[198]ms.
查看执行计划性能
explain select * from `kmd_tb_goods` where (`item_id` = 41928087111) and `kmd_tb_goods`.`deleted_at` is null limit 1
能够看出有有索引 tb_goods_item_id_index
,可是 type=ALL
,这就很奇怪奇怪了,有索引为何没走索引?
查看表结构:优化
show create table kmd_tb_goods CREATE TABLE `kmd_tb_goods` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `item_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '商品itemId', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `tb_goods_item_id_index` (`item_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
发现item_id
是 varchar 类型,可是查询语句是 int 类型,致使字段隐式转换扫描全表,因此性能差。code
把item_id
改为字符串类型就能够了,避免了隐式转换扫描全表。blog
select * from `kmd_tb_goods` where (`item_id` = '41928087111') and `kmd_tb_goods`.`deleted_at` is null limit 1
查看执行计划
索引
手动执行语句,耗时:[2]ms。从原来的198ms优化到了2ms,性能差了近100倍。ci