mysql什么情况会扫描所有_造成MySQL全表扫描的原因
全表掃描是數(shù)據(jù)庫搜尋表的每一條記錄的過程,直到所有符合給定條件的記錄返回為止。通常在數(shù)據(jù)庫中,對無索引的表進(jìn)行查詢一般稱為全表掃描;然而有時候我們即便添加了索引,但當(dāng)我們的SQL語句寫的不合理的時候也會造成全表掃描。
以下是經(jīng)常會造成全表掃描的SQL語句及應(yīng)對措施:
1. 使用null做為判斷條件
如:select account from member where nickname = null;
建議在設(shè)計(jì)字段時盡量將字段的默認(rèn)值設(shè)為0,改為select account where nickname = 0;
2. 左模糊查詢Like %XXX%
如:select account from member where nickname like ‘%XXX%’ 或者 select account from member where nickname like ‘%XXX’
建議使用select account from member where nickname like ‘XXX%’,如果必須要用到做查詢,需要評估對當(dāng)前表全表掃描造成的后果; 劉加?xùn)|@酷聽說
3. 使用or做為連接條件
如:select account from member where id = 1 or id = 2;
建議使用union all,改為 select account from member where id = 1 union all select account from member where id = 2;
4. 使用in時(not in)
如:select account from member where id in (1,2,3)
如果是連續(xù)數(shù)據(jù),可以改為select account where id between 1 and 3;當(dāng)數(shù)據(jù)較少時也可以參考union用法;
或者:select account from member where id in (select accountid from department where id = 3 ),可以改為select account from member where id exsits (select accountid from department where id = 3)
not in 可以對應(yīng) not exists;
5.使用not in時
如select account where id not in (1,2,3)
6.使用!=或<>時
建議使用 ,>=,between等;
7.對字段有操作時也會引起權(quán)標(biāo)索引
如select account where salary * 0.8 = 1000 或者 select account where sustring(nickname,1,3) = ‘zhangxiaolong’;
8.使用count(*)時
如select count(*) from member;
建議使用select count(1) from member;
9.使用參數(shù)做為查詢條件時
如select account from member where nickname = @name
由于SQL語句在編譯執(zhí)行時并不確定參數(shù),這將無法通過索引進(jìn)行數(shù)據(jù)查詢,所以盡量避免; 劉加?xùn)|@酷聽說
當(dāng)不規(guī)范的寫法造成全表掃描時,會造成CPU和內(nèi)存的額外消耗,甚至?xí)?dǎo)致服務(wù)器崩潰。在團(tuán)隊(duì)協(xié)作中難免會遇到一些初學(xué)者,除了安排合理的任務(wù)外,資深的工程師也要做好Code Review。否則當(dāng)我們有海量數(shù)據(jù)時,不規(guī)范的語句會帶來很嚴(yán)重的后果,一定要慎重、慎重。
文章鏈接為:https://blog.csdn.net/u012501054/article/details/80361447
總結(jié)
以上是生活随笔為你收集整理的mysql什么情况会扫描所有_造成MySQL全表扫描的原因的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux修改容器内的mysql端口映射
- 下一篇: mysql登录抓包_MySQL登录验证的