什么时候用不到索引?
1、索引列上使用函數(shù)(replace\SUBSTR\CONCAT\sum count avg)、表達(dá)式、計(jì)算(+ - * /):
explain SELECT * FROM `t2` where id+1 = 4;2、字符串不加引號(hào),出現(xiàn)隱式轉(zhuǎn)換
ALTER TABLE user_innodb DROP INDEX comidx_name_phone; ALTER TABLE user_innodb add INDEX comidx_name_phone (name,phone); explain SELECT * FROM `user_innodb` where name = 136; explain SELECT * FROM `user_innodb` where name = '136';3、like 條件中前面帶%
where 條件中l(wèi)ike abc%,like %2673%,like %888 都用不到索引嗎?為什么?
explain select *from user_innodb where name like 'wang%'; explain select *from user_innodb where name like '%wang';過濾的開銷太大,所以無法使用索引。這個(gè)時(shí)候可以用全文索引。
4、負(fù)向查詢
NOT LIKE 不能:
explain select *from employees where last_name not like 'wang'!= (<>)和NOT IN 在某些情況下可以:
explain select *from employees where emp_no not in (1) explain select *from employees where emp_no <> 1注意一個(gè)SQL 語句是否使用索引,跟數(shù)據(jù)庫版本、數(shù)據(jù)量、數(shù)據(jù)選擇度都有關(guān)系。
其實(shí),用不用索引,最終都是優(yōu)化器說了算。
優(yōu)化器是基于什么的優(yōu)化器?
基于cost 開銷(Cost Base Optimizer),它不是基于規(guī)則(Rule-Based Optimizer),也不是基于語義。怎么樣開銷小就怎么來。
https://docs.oracle.com/cd/B10501_01/server.920/a96533/rbo.htm#38960
https://dev.mysql.com/doc/refman/5.7/en/cost-model.html
?
總結(jié)
以上是生活随笔為你收集整理的什么时候用不到索引?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。