常見sql語句效率優化方式
首先介紹幾條優化原則:
- 儘量避免where中包含子查詢;
- where條件中,過濾量最大的條件放在where子句最後;
- 採用繫結變數有助於提高效率;
- 在索引列上使用計算、改變索引列的型別、在索引列上使用!=將放棄索引;
- 避免在索引列上使用is null和is not null;
- 使用索引的第一個列;
- 用union-all替代union;
- like ‘text%’使用索引,但like ‘%text’不使用索引;
- select a, b from tab 比 select * from tab 效率高。
一、“like '%%'”的優化,建議使用instr(?,?)效率高
單表有超大數量級的數
1、oracle和mysql中
如果有索引的情況下,使用like 'aa%'或者like '%aa'效率較高,因為如果是like "%aa%"那麼會導致全表掃描!效率非常低!
如果沒有索引,那麼最好使用instr(stpm,字串)函式解決問題
舉例:
select * from xslsb where spmc like '%毛線%'; //效率很低
select * from xslsb where (instr(spmc,'毛線'))>0; //效率高
2、sql server中
2005以後,採用contains(spmc,'毛線')函式
二、批量插入
如果一條一條插入,那麼效率很低
insert into t_user values(?,?,?);
所以採用批量
insert into t_user select * from t_user2;
其他延伸:t_user 表字段要和t_user2欄位的結構和名稱一致
三、exists和in的效率
exists相對較高,適用於外表小,內表大的情況
select * from 外表小 where exists( select * from 內表大);
in相對較低,適用於外表大,內表小的情況
select * from 外表大 where 欄位 in (select 欄位 from 內表小);
如果內表和外表差不多,那麼exists和in效率差不多!
四、對查詢的條件新增索引
1、mysql
create index t_user_index on t_user(username);
drop index t_user_index on t_user; --刪除索引
2、oracle
create index t_user_index on t_user(username);
drop index t_user_index; ---刪除索引
五、使用union all 而少用union
union all執行的內部機制少
union 在表聯合查詢後還會進行篩選操作,費時!
六、連續值查詢
1、使用between and
原因:不會全表查詢
2、不使用in()
原因:導致全表查詢,效率低
七、應儘量避免在where子句中對欄位進行函式操作,這將導致引擎放棄使用索引而進行全表掃描。如:
select id from t_user where substring(name,1,3) = 'abc' -–name以abc開頭的id
改為:select id from t where name like 'abc%'
八、儘量避免大事務操作,提高系統併發能力。
九、跨oracle使用者訪問
select count(*) from (select hykh from user.tablewhere scsj>=to_date('2015-11-01','yyyy-MM-dd') group by hykh);
user代表使用者
table代表user中的table表
十、建立臨時表可以提高查詢速度
如果在1000萬的資料中查詢結果,那麼以下第二種查詢效率會高很多倍!
(1)select * from t_user where name='suns';
(2)select * from t_user tu,user us where tu.id=us.id and us.name='suns';
十一、使用mysql 的擴充套件語句replace into 與insert into 的注意
1、insert into 效率低,但是通用效能很好
2、replace into 效率高 ,但是如果表中有自增長的主鍵,那麼一定要謹慎選擇使用,因為如果主鍵的增長id一旦達到最大後就無法繼續增長了!