理解NULL是如何影響IN和EXITS語句的
2024-07-21 02:34:31
供稿:網(wǎng)友
從表面上看,IN和EXITS的SQL語句是可互換和等效的。然而,它們?cè)谔幚鞺ULL數(shù)據(jù)時(shí)會(huì)有很大的差別,并導(dǎo)致不同的結(jié)果。問題的根源是在一個(gè)Oracle數(shù)據(jù)庫中,一個(gè)NULL值意味著未知變量,所以操作NULL值的比較函數(shù)的結(jié)果也是一個(gè)未知變量,而且任何返回NULL的值通常也被忽略。 例如,以下查詢都不會(huì)返回一行的值:
select 'true' from dual where 1 = null;
select 'true' from dual where 1 != null;
只有IS NULL才能返回true,并返回一行:
select 'true' from dual where 1 is null;
select 'true' from dual where null is null;
當(dāng)你選擇使用IN,你將會(huì)告訴SQL選擇一個(gè)值并與其它每一值相比較。假如NULL值存在,將不會(huì)返回一行,即使兩個(gè)都為NULL。
select 'true' from dual where null in (null);
select 'true' from dual where (null,null) in ((null,null));
select 'true' from dual where (1,null) in ((1,null));
一個(gè)IN語句在功能上相當(dāng)于 = ANY語句:
select 'true' from dual where null = ANY (null);
select 'true' from dual where (null,null) = ANY ((null,null));
select 'true' from dual where (1,null) = ANY ((1,null));
當(dāng)你使用一個(gè)EXISTS等效形式的語句,SQL將會(huì)計(jì)算所有行,并忽略子查詢中的值。
select 'true' from dual where exists (select null from dual);
select 'true' from dual where exists (select 0 from dual where null is null);
IN 和EXISTS在邏輯上是相同的。IN語句比較由子查詢返回的值,并在輸出查詢中過濾某些行。EXISTS語句比較行的值,并在子查詢中過濾某些行。對(duì)于NULL值的情況,行的結(jié)果是相同的。
select ename from emp where empno in (select mgr from emp);
select ename from emp e where exists (select 0 from emp where mgr = e.empno);
然而當(dāng)邏輯被逆向使用,即NOT IN 及NOT EXISTS時(shí),問題就會(huì)產(chǎn)生:
select ename from emp where empno not in (select mgr from emp);
select ename from emp e where not exists (select 0 from emp where mgr =
e.empno );
NOT IN 語句實(shí)質(zhì)上等同于使用=比較每一值,假如測試為FALSE或者NULL,結(jié)果為比較失敗。例如:
select 'true' from dual where 1 not in (null,2);
select 'true' from dual where 1 != null and 1 != 2;
select 'true' from dual where (1,2) not in ((2,3),(2,null));
select 'true' from dual where (1,null) not in ((1,2),(2,3));
這些查詢不會(huì)返回任何一行。第二個(gè)查詢語句更為明顯,即 1 != null ,所以整個(gè)WHERE都為false。然而這些查詢語句可變?yōu)椋?br />
select 'true' from dual where 1 not in (2,3);
select 'true' from dual where 1 != 2 and 1 != 3;
你也可以使用NOT IN查詢,只要你保證返回的值不會(huì)出現(xiàn)NULL值:
select ename from emp where empno not in (select mgr from emp where mgr is not
null );
select ename from emp where empno not in (select nvl(mgr,0) from emp);
通過理解IN, EXISTS, NOT IN,以及NOT EXISTS之間的差別,當(dāng)NULL出現(xiàn)在任一子查詢中時(shí),你可以避免一些常見的問題。