1.select * from
* 一定要(yao)要(yao)慎用,最好是只返回你需(xu)要(yao)的列,否則效(xiao)率會(hui)很低
2.游標要慎用
之前在實際項目中,因為內存不(bu)足的原因,使用游標從數(shu)據庫中讀數(shu)據,
游(you)標實際上(shang)就是分批放(fang)入(ru)內(nei)存,實際上(shang)減小(xiao)了內(nei)存的占用,但效率會(hui)變低
3.索引建立在需要查詢較為頻繁的列
要(yao)建立在(zai)經(jing)常做查詢的列上(shang)
4.防止索引失效是很關(guan)鍵的
(1) 最左前綴(zhui)法(fa)則:比如create index 了三(san)個索引,進(jin)行查(cha)詢(xun)匹配時,要(yao)按順序走索引
ALTER TABLE `table_name` ADD INDEX index_name ( `column1`, `column2`, `column3` )
查詢時符合(he)最(zui)左前綴:
select id from tablename where column1 = “spx”;
select id from tablename where column1 = “spx” and column2= "spx"
select id from tablename where column1 = “spx” and column2 ="spx" and column3="spx"
違背(bei)最(zui)左前(qian)綴,索引(yin)全部失效:
select id from tablename where column2 = “spx” and column3="spx"
符合最(zui)左(zuo)前綴,只有(you)左(zuo)列索(suo)引(yin)生效(xiao)(跳躍了某一(yi)索(suo)引(yin)列):
select id from tablename where column1 = “spx” and column3="spx"
(2) 索引(yin)列進行運算操作,索引(yin)將失效
(3)使(shi)用(yong)or 時如(ru)果or之(zhi)前是索(suo)引列,or之(zhi)后不是那么索(suo)引失效,所(suo)以限制(zhi)條(tiao)件字段沒有索(suo)引就少用(yong)or;
解決方(fang)案(an):可以使用(yong)union 或者(zhe)union all 效果更(geng)好,但是(shi)盡量要使用(yong) union all ,
因為前者要加(jia)結(jie)果(guo)集合并后再(zai)進行過濾操作,增(zeng)大cpu運算,但是union all 前提是倆個(ge)結(jie)果(guo)集沒有重復數(shu)據(ju)
column1 --索引(yin)列 column 2 -- 不(bu)是索引(yin)列
索引失效:select id from tablename where conlumn1 ="spx" or conlumn2="spx";
解(jie)決(jue): select id from tablename where conlumn1=“spx”
union all
select id from tablename where conlumn2="spx";
(4)模糊查詢時(shi),以%開(kai)頭,索引失(shi)效,盡量都寫(xie)成尾部(bu)模糊匹配
(5) is NULL,is not NULL 有時索(suo)引失效
(6) 索(suo)引列數據類型(xing)不匹配,比如 column1 的(de)類型(xing)是varchar
eg: select id from tablename where column1 = 1; 沒(mei)有加引(yin)號(hao),會自動轉(zhuan)類型導致索引(yin)失(shi)效
5.復合索引大多數情況下效率高于單列索引
因為多條件聯合(he)查詢時,mysql優(you)化(hua)器會評估哪個條件的索(suo)引(yin)的效率高(gao),會去選(xuan)擇(ze)最(zui)佳(jia)的索(suo)引(yin)
6.EXPLAIN的使用
要經常使(shi)用 EXPLAIN 來(lai)查看(kan) sql 的(de)執行計劃(hua),這算一個很(hen)好的(de)習慣,比較sql的(de)性(xing)能(neng),查看(kan)該語(yu)句是否使(shi)用了索(suo)引等等,真的(de)很(hen)重(zhong)要!!
7. in 和 exists , not in 和 not exists 小結
select *from tablename1 where id in (select id from tablename2)
上面的sql等于下面這個
select *from tablename1 where exists(select id tablename2 where tablename2.id = tablename1.id)
根據驅動的(de)(de)順序可知(zhi),in先執行(xing)子查詢,in適合(he)于(yu)外表大而內表小的(de)(de)情況,exists先對外表做loop循環,所(suo)以適合(he)于(yu)外表小而內表大的(de)(de)情況
not in 內外表(biao)都進行全表(biao)掃描,而 not exists 得子(zi)查詢依然能用到表(biao)上(shang)的索引,所以一(yi)定要使用 not exists