like的使用
萬用字元出現在首位,無法使用索引,反之可以。
-- 無法使用索引
select..
from..
where name like
'%t%'
;-- 可以使用索引
select..
from..
where name like
't%'
;
or的使用
索引列上的or操作會造成全表掃瞄。在索引列上,可以使用union替換or操作。
-- 低效:
select columna ,columnb ,columnc from location where columna=
10or columnc =
'melbourne'
-- 高效:
select columna , columnb , columnc from location where columna =
10union
select columna , columnb , columnc from location where columnc =
'melbourne'
in 或 not in的使用
in和not in 要慎用,否則會導致全表掃瞄。
--between替換in
1select columna from a where num in(1
,2,3
)--會造成全表掃瞄
2select columna from a where num between
1and
3--不會造成全表掃瞄
--exist替換in
1select columna from a where num in
(select num from b )
--會造成全表掃瞄
2select num from a where num exists
(select
1from b where b.num = a.num)
--不會造成全表掃瞄
--left join替換in
1select columna from a where num in
(select num from b)
--會造成全表掃瞄
2select columna from a left
join b on a.num = b.num --不會造成全表掃瞄
order by
order by子句中不要使用非索引列或巢狀表示式,這樣都會導致效能降低。
null列
null列使用索引沒有意義,任何包含null值的列都不會被包含在索引中。因此where語句中的is null或is not null的語句優化器是不允許使用索引的。
函式在where條件裡不要在索引列上使用函式或者表示式,這樣會停止使用索引,進行全表掃瞄,如下:
-- 錯誤
select … from a where columna *
12>
25000
;-- 正確
select … from a where columna >
25000/12
;
2.使用臨時表存放中間結果
對於那種需要進行多重巢狀的情況,可以使用臨時表、with as臨時快取、物化檢視等方式先將資料落下來再進行操作。
SQL的優化技巧
一 一些常見的sql實踐 1 負向條件查詢不能使用索引 not in not exists都不是好習慣 可以優化為in查詢 2 前導模糊查詢不能使用索引 而非前導模糊查詢則可以 3 資料區分度不大的字段不宜使用索引 原因 性別只有男,女,每次過濾掉的資料很少,不宜使用索引。經驗上,能過濾80 資料時...
SQL多表優化思路
一 驅動表選擇 左右連線可以指定驅動表,但是inner join無法指定,一般是系統自動判定 1.當使用left join時,左表是驅動表,右表是被驅動表 2.當使用right join時,右表時驅動表,左表是驅動表 3.當使用join時,mysql會選擇資料量比較小的表作為驅動表,大表作為被驅動表...
sql優化技巧
1.比較運算子能用 就不用 增加了索引的使用機率 2.事先知道只有一條查詢結果時,使用 limit 1 limit 1 可以避免全表掃瞄,找到對應結果就不會再繼續掃瞄了 3.選擇合適的資料型別很重要 能用tinyint就不用smallint,能用smallint就不用int,磁碟和記憶體消耗越小越好...