日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql什么情况会扫描所有_造成MySQL全表扫描的原因

發(fā)布時間:2025/3/21 数据库 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql什么情况会扫描所有_造成MySQL全表扫描的原因 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

全表掃描是數(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。