mysql的explain的用途,利用Explain来分析和优化你的mysql
下面我用一個例子來演示如何使用explain來優化mysql查詢:
需求是這樣的,在一個有1300+萬條的mysql表中查出一個時間段內的數據,聯表查詢:select?d2.name?as?'大區'?,d1.name?as?'事業部',?et_station.name?as?'小區',et_device.direction?as?'方向',count(1)?as?'次數'
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語句直接執行,查詢需要9秒完成,可想而知,在實際應用中,這條sql會有非常大的隱患,我們來用explain分析下:
可以看到,主表采用了全表掃描(type:ALL),mysql查詢了13149541行記錄(rows),這樣的效率非常之低,業務需求不能更改的情況下,在生產環境執行可能會跑跨數據庫,下面我們簡單做處理:
考慮到業務需求,經常用時間來作為條件,查詢數據導出報表,我們來給time字段加上索引。
再來explain分析下:explain(select?d2.name?as?'大區'?,d1.name?as?'事業部',?et_station.name?as?'小區',et_device.direction?as?'方向',count(1)?as?'次數'
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)
下面我們看結果:
對比上一張圖我們能看到,type由ALL變成了range(范圍檢索),因為我們給time字段上了索引,mysql可以利用索引來檢查行。rows由1300多萬變成1,表示這次只用查詢1行就完成了查詢;
然后我們執行sql查詢,整個查詢只需要0.3秒完成。
當然了,這只是個例子,并不是可以適用任何業務需求的場景,explain可以幫我們分析出很多問題,大家可以去多多了解。
原創文章如轉載,請注明出處,本文首發于彭超的博客
打賞
微信掃一掃,打賞作者吧~
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的mysql的explain的用途,利用Explain来分析和优化你的mysql的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql元数据死锁日志,MySQL 实
- 下一篇: linux cmake编译源码,linu