總結:
NULL值不能用用來+-*/, 不能用來<>, not in
否則返回空或NULL
即 不可以 1. not in (select null),返回空
2. not exists 如果條件中有null值, 外層查詢的null值會被返回。
3. in 和 exists 均會過濾掉條件中null值
not In 相當於 <> all,如果 Not In 后面跟的是子查詢的話,子查詢中只要包含一個 null 的返回值,則會造成
整個 Not in 字句返回空值,結果就是查詢不會返回任何結果。
而 in 相當於 =any 的意思,可以有效處理子查詢中返回空值的情況,返回正確的結果。
------------------------------------------------------------------------------------------------------
not in 示例:--該例子想要返回沒有下屬的職員的姓名,如果子查詢中有空值返回的話,則整個查詢將沒有結果返回
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN (SELECT mgr.manager_id FROM employees mgr)
說明:
Null Values in a Subquery
The SQL statement in the slide attempts to display all the employees who do not have any
subordinates. Logically, this SQL statement should have returned 12 rows. However, the SQL
statement does not return any rows. One of the values returned by the inner query is a null value and,
therefore, the entire query returns no rows
The reason is that all conditions that compare a null value result in a null. So whenever null values
are likely to be part of the resultsset of a subquery, do not use the NOT INoperator. The NOT IN
operator is equivalent to <> ALL.
---------------------------------------------------------------------------------------------------------
in 的示例:
Notice that the null value as part of the results set of a subquery is not a problem if you use the IN
operator. The IN operator is equivalent to =ANY. For example, to display the employees who have
subordinates(下屬), use the following SQL statement:
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id IN (SELECT mgr.manager_id FROM employees mgr);
---------------------------------------------------------------------------------------------------------
Alternatively, a WHERE clause can be included in the subquery to display all employees who do not
have any subordinates:
--使用 Not In 的話,要注意除掉子查詢中將要返回的空值
SELECT last_name
FROM employees
WHERE employee_id NOT IN
(SELECT manager_id FROM employees WHERE manager_id IS NOT NULL);