子查詢就是指在一個select語句中嵌套另一個select語句。
any,in,some,all分別是子查詢關鍵詞之一,
any 可以與=、>、>=、<、<=、<>結合起來使用,分別表示等於、大於、大於等於、小於、小於等於、不等於其中的任何一個數據。
all可以與=、>、>=、<、<=、<>結合是來使用,分別表示等於、大於、大於等於、小於、小於等於、不等於其中的其中的所有數據。
他們進行子查詢的語法如下:
operand comparison_operator any (subquery); operand in (subquery); operand coparison_operator some (subquery); operand comparison_operator all (subquery);
any,all關鍵字必須與一個比較操作符一起使用。any關鍵詞可以理解為“對於子查詢返回的列中的任一數值,如果比較結果為true,則返回true”。
例如:
select s1 from t1 where s1 > any (select s1 from t2);
假設表t1中有一行包含(10),t2包含(21,14,6),則表達式為true;如果t2包含(20,10),或者表t2為空表,則表達式為false。如果表t2包含(null,null,null),則表達式為unkonwn。
all的意思是“對於子查詢返回的列中的所有值,如果比較結果為true,則返回true”
例如:
select s1 from t1 where s1 > all(select s1 from t2);
假設表t1中有一行包含(10)。如果表t2包含(-5,0,+5),則表達式為true,因為10比t2中的查出的所有三個值大。如果表t2包含(12,6,null,-100),則表達式為false,因為t2中有一個值12大於10。如果表t2包含(0,null,1),則表達式為unknown。如果t2為空表,則結果為true。
not in 是 “<>all”的別名,用法相同。
語句in 與“=any”是相同的。
例如:
select s1 from t1 where s1 = any (select s1 from t2); select s1 from t1 where s1 in (select s1 from t2);
語句some是any的別名,用法相同。
例如:
select s1 from t1 where s1 <> any (select s1 from t2); select s1 from t1 where s1 <> some (select s1 from t2);
在上述查詢中some理解上就容易了“表t1中有部分s1與t2表中的s1不相等”,這種語句用any理解就有錯了。