什么是慢sql培遵?慢sql的定義挪丢,目前共識(shí)是rt>1S,當(dāng)存在1s以上的sql喜命,qps比較高(150)時(shí)候沟沙,大概率會(huì)發(fā)生線上問題
風(fēng)險(xiǎn)維度:
執(zhí)行時(shí)間rt:執(zhí)行時(shí)間超過1s
平均掃描行數(shù):掃描行數(shù)過高則一般說明sql有優(yōu)化空間
全表掃描:一般是由于沒有配置索引
平均返回行數(shù):返回行數(shù)過高,對(duì)系統(tǒng)邏輯有一定的風(fēng)險(xiǎn)
索引覆蓋:當(dāng)前sql不是最佳索引
索引知識(shí):
查看表索引:show index from table_name
查看sql語句影響行數(shù):explain select * from user where phone=‘xxx’
索引錯(cuò)用:
1.類型隱士轉(zhuǎn)換
wrong: select * from user where phone=xxx
right: select * from user where phone=‘xxx’
2.索引字段使用函數(shù)或者運(yùn)算
wrong: select * from user where Date(create_at)=‘2019-12-12’
right:select * from user where create_at>‘2019-12-12’ AND create_at<'2019-12-13'
3.謹(jǐn)慎使用OR壁榕,OR中只要有一個(gè)沒有索引矛紫,就會(huì)走全表掃描
select name from user where id=10 and sex=‘男’,sex沒有索引牌里,導(dǎo)致走全表
4.Like 正確使用颊咬,like ‘%xxx’ |like ‘%xxx%’,會(huì)讓索引失效牡辽,但可以使用like‘xx%’
5.不應(yīng)該使用select *喳篇,而是需要什么查什么
select name from user,當(dāng)name有索引的時(shí)候态辛,直接掃描索引愉昆,不需要再掃表柜去,索引覆蓋
6.謹(jǐn)慎使用order by導(dǎo)致的內(nèi)存排序
7.當(dāng)搜索范圍很大時(shí),mysql估計(jì)使用全表掃描要比索引快,則不適用索引