最近在分析一条SQL,这条SQL执行时间去到2秒以上。SQL如下:
sql
select
count(d.id)
from
t_msg d
where
d.userid='12456'
and d.isread=0
AND d.msgnumber<> 'NEW-JCPT003'
表上索引有 idx_userid(userid),这条SQL是一条比较标准的统计SQL,涉及字段也少。
虽然表数据有一百多万,但加了索引,explain一下只扫描记录5w多,按道理耗时很少。仔细分析是查询语句中用到了非索引字段,如果能把语句中涉及到的字段都加入索引,这样SQL在执行中可以减少回表时间,回表时间在SQL执行中占比挺大的。
马上修改索引 idx_userid(userid,isread,msgnumber),执行一下只耗时0.5秒了。这里isread和msgnumber两列的值属于枚举类型,加入索引在查询时效果没那么大,而且msgnumber这里是<>,用不上索引。会有人认为对这两个字段加索引没意义,但如果从减少回表的角度考虑,加索引意义很大
后面又碰到一条类似的SQL
sql
select
count(*) as "ALL",
sum(CASE
WHEN d.code='A' THEN 1
ELSE 0
END) AS "A",
sum(CASE
WHEN d.code='B' THEN 1
ELSE 0
END) AS "B",
sum(CASE
WHEN d.code='C' THEN 1
ELSE 0
END) AS "C",
sum(CASE
WHEN d.code='D' THEN 1
ELSE 0
END) AS "D",
sum(CASE
WHEN d.code='E' THEN 1
ELSE 0
END) AS "E",
sum(CASE
WHEN d.code='F' THEN 1
ELSE 0
END) AS "F",
sum(CASE
WHEN d.code='G' THEN 1
ELSE 0
END) AS "G"
FROM
t_msg d
WHERE
1=1
AND d.msgitemnumber <> 'NEW-JCPT003'
and d.userid='123456' limit 1
二话不说直接修改索引idx_userid(userid,isread,msgnumber,code) ,耗时也降到0.5秒以下了