数据库索引原理实例
create table t1
(
? c1 varchar2(10),
? c2 varchar2(20),
? n1 number(10,0),
? d1 date
);
alter table T1 add constraint pk_t1 primary key (C1);
create index idx_t1_n1_c2 on T1 (n1, c2);
create index idx_t1_d1 on T1 (d1);
select * from t1 where c1='1’; ?--使用索引pk_t1
select * from t1 where c1=1; ? ? ?--未使用索引,做了隱式轉(zhuǎn)換,相當(dāng)于where to_number(c1)=1
select * from t1 where c2='1’; --未使用索引,因c2是索引的第2個(gè)字段
create index idx_t1_n1 on T1 (n1); --重復(fù)索引,與idx_t1_n1_c2重復(fù)
select * from t1 where d1=to_date('2020-10','yyyy-mm'); --使用索引idx_t1_d1
select * from t1 where to_char(d1,'yyyymmdd’)='20201002’; --未使用索引,不存在to_char(d1,'yyyymmdd’)的函數(shù)索引
解決辦法:改為d1 between to_date('20200102 00:00:00','yyyymmdd hh24:mi:ss') and to_date('20200102 23:59:59','yyyymmdd hh24:mi:ss')
也可以執(zhí)行create index idx_t1_tochard1 on T1 (to_char(d1,'yyyymmdd'));后上一句可以使用到索引idx_t1_tochard1。
select * from t1 where to_char(d1,'YYYYMMDD’)='20201002’; ? ? --未使用索引,函數(shù)中大小寫(xiě)不相同
select * from t1 where to_char(d1,'yyyy-mm-dd’)='2020-10-02’; --未使用索引,函數(shù)不相同
select * from t1 where n1 is null; ? ?--未使用索引,is null無(wú)法使用到索引
select * from t1 where n1 is not null; --未使用索引,is not null無(wú)法使用到索引
解決辦法: alter table T1 modify n1 default 0 not null; ? 查詢(xún)時(shí)n1 is null改為n1=0
select * from t1 where c1 like '張%'; --使用索引pk_t1
select * from t1 where c1 like '%張'; --未使用索引
總結(jié)
- 上一篇: [数论] 小球碰撞
- 下一篇: mysql句柄是什么_什么是句柄?为什么