讓Oracle索引Null列


1.建立環境

create table t1 (id int,name varchar(10),age int);

create table t2 (id int,name varchar(10),age int);

insert into t1 values (1,’abc’,33);

insert into t1 values (2,’’,31);

insert into t2 values (1,’abc’,33);

insert into t2 values (2,’’,31);

insert into t1 values (3,’xyz’,34);

2. Null的問題

SQL> select * from t2 where name not in (select name from t1);

no rows selected

按照邏輯這里應該返回

ID NAME AGE
————— ————— —————

3 xyz 34

解決方法

select * from t2 where name not in (select nvl(name,0) from t1);

select * from t2 where not exists (select name from t1 where t2.id=t1.id);

select * from t2 where name not in (select name from t1 where t2.id=t1.id);

注意這里這樣寫select * from t2 where not exists (select name from t1);也是不行的

3其他-null建立到復合索引里邊使null也可以走索引

講兩個NULL與索引的小技巧

3.1 既然NULL是可以進復合索引的,在我們需要對NULL進行索引時,就可以構造一個“偽復合索引”:

CREATE INDEX my_index ON my_table(my_column,0);

后面這個零就是加入的偽列。這樣以后在有 my_column IS NULL 的條件就可以利用索引了(當然最終使用與否還得由CBO決定)。

3.2 不想索引的行,即使不是NULL, 也可用函數把它剔除。

假設有status_id列,里面有0:未處理,1:已處理 兩種狀態,我們關心的僅僅是0的行,處理完就會改成1. 這樣表中0的行僅僅是少數,大部分是1的行,數據量多了BTREE索引的維護就有開銷。

這時可以建立這樣的索引:

CREATE INDEX my_index ON my_table(DECODE(status_id,0,0));

它只對0行數據進行索引。當你要取未處理數據時,SELECT * FROM my_table WHERE DECODE(status_id,0,0)=0 就可以高效利用索引。

以上測試根據 yangtingkun 發表於: 2011.05.19 23:46 的blog 《常數復合索引應用案例》進行的測試。

—EOF—


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM