mysql優化經驗

1.避免 select *  用具體的字段代替*,不要返回無用的字段

2.應該儘量避免在where字句中使用!=或<>操作符

3.應該儘量避免在where字句中對字段進行null判斷

    select id from 表名 where num is null; (判斷是否爲null不能使用=)

可以在num上設置默認值,比如0,確保表中沒有null值,然後這樣查詢:

select id from 表名 where num=0;

4.應該儘量避免在where字句中使用or來連接條件

select id from 表名 num=10 or num=20;

可以這樣查詢

select id from 表名 where num=10;

union all

select id from 表名 where num=20;

5.使用like模糊查詢會導致全表掃描

如 select id from t where num like '%123%'

若要提高效率可以使用全文檢索技術

6.儘量避免in 和 not in

select id from t  name in(1,2,3,4);

對於連續的數值可以用between 

select id from t between  1 and 4;

使用exists代替in,是一個好的選擇

select num from a where num in(select num from b);

用下面的語句替換

select num from a where exists(select )

 not in 優化

select ID,name from Table_A where ID not in (select ID from Table_B)

這句是最經典的not in查詢了。改爲表連接代碼如下:

select Table_A.ID,Table_A.name from Table_A left join Table_B on Table_A.ID=Table_B.ID and Table_B.ID is null
或者:
select Table_A.ID,Table_A.name from Table_A left join Table_B on Table_A.ID=Table_B.ID where Table_B.ID is null

7.應該儘量避免在where字句中對字段進行表達式操作,如

select id from t where num/2=100;

應該爲:

select id from where num=100*2;

8.不要在where字句中的“=”左邊進行函數、算數運算或其他表達式運算,否則系統將可能無法正確使用索引

9.儘量使用數字型字段

    一部分開發人員和數據庫管理人員喜歡把包含數值信息的字段,設計爲字符型,這會降低查詢和連接的性能,並會增加存儲開銷,這是因爲引擎在處理查詢和連接會逐個比較字符串中每一個字符,而對於數字型而言只需要比較一次就夠了

10.能夠用distinct就不要用group by

11.程序中如果一次性對同一個表插入多條數據,把他拼成一條效率會更高,如下句

insert into person(name,age) values(‘xboy’, 14); 

insert into person(name,age) values(‘xgirl’, 15); 

insert into person(name,age) values(‘nia’, 19); 

把它拼成一條語句執行效率會更高.

 insert into person(name,age) values(‘xboy’, 14), (‘xgirl’, 15),(‘nia’, 19);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章