忽然收到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