mysql的explain的用途,利用Explain来分析和优化你的mysql
下面我用一個(gè)例子來演示如何使用explain來優(yōu)化mysql查詢:
需求是這樣的,在一個(gè)有1300+萬條的mysql表中查出一個(gè)時(shí)間段內(nèi)的數(shù)據(jù),聯(lián)表查詢:select?d2.name?as?'大區(qū)'?,d1.name?as?'事業(yè)部',?et_station.name?as?'小區(qū)',et_device.direction?as?'方向',count(1)?as?'次數(shù)'
from?et_exception
join?et_station?on?et_station.id=et_exception.station
join?et_device?on?et_device.id=et_exception.device
join?et_department?as?d1?on?d1.id=et_station.dept
join?et_department?as?d2?on?d1.parent=d2.id
where
`et_exception`.`time`>=UNIX_TIMESTAMP('2017/04/24?00:00:00')
and
`et_exception`.`time`
group?by?et_exception.station,et_device.direction
這條SQL語句直接執(zhí)行,查詢需要9秒完成,可想而知,在實(shí)際應(yīng)用中,這條sql會(huì)有非常大的隱患,我們來用explain分析下:
可以看到,主表采用了全表掃描(type:ALL),mysql查詢了13149541行記錄(rows),這樣的效率非常之低,業(yè)務(wù)需求不能更改的情況下,在生產(chǎn)環(huán)境執(zhí)行可能會(huì)跑跨數(shù)據(jù)庫,下面我們簡單做處理:
考慮到業(yè)務(wù)需求,經(jīng)常用時(shí)間來作為條件,查詢數(shù)據(jù)導(dǎo)出報(bào)表,我們來給time字段加上索引。
再來explain分析下:explain(select?d2.name?as?'大區(qū)'?,d1.name?as?'事業(yè)部',?et_station.name?as?'小區(qū)',et_device.direction?as?'方向',count(1)?as?'次數(shù)'
from?et_exception
join?et_station?on?et_station.id=et_exception.station
join?et_device?on?et_device.id=et_exception.device
join?et_department?as?d1?on?d1.id=et_station.dept
join?et_department?as?d2?on?d1.parent=d2.id
where
`et_exception`.`time`>=UNIX_TIMESTAMP('2017/04/24?00:00:00')
and
`et_exception`.`time`
group?by?et_exception.station,et_device.direction)
下面我們看結(jié)果:
對(duì)比上一張圖我們能看到,type由ALL變成了range(范圍檢索),因?yàn)槲覀兘otime字段上了索引,mysql可以利用索引來檢查行。rows由1300多萬變成1,表示這次只用查詢1行就完成了查詢;
然后我們執(zhí)行sql查詢,整個(gè)查詢只需要0.3秒完成。
當(dāng)然了,這只是個(gè)例子,并不是可以適用任何業(yè)務(wù)需求的場(chǎng)景,explain可以幫我們分析出很多問題,大家可以去多多了解。
原創(chuàng)文章如轉(zhuǎn)載,請(qǐng)注明出處,本文首發(fā)于彭超的博客
打賞
微信掃一掃,打賞作者吧~
超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的mysql的explain的用途,利用Explain来分析和优化你的mysql的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql元数据死锁日志,MySQL 实
- 下一篇: 腾讯云安装mysql本地主机名,腾讯云服