Oracle Study之---Oracle IN和NOT IN的使用
Oracle Study之---Oracle IN和NOT IN的使用
NOT IN 与 IN 的区别:
------------------------------------------------------------------------------------------------------
not In 相当于<> all,如果 Not In 后面跟的是子查询的话,子查询中只要包含一个 null 的返回值,则会造成
整个 Not in 字句返回空值,结果就是查询不会返回任何结果。
而 in 相当于=any的意思,可以有效处理子查询中返回空值的情况,返回正确的结果。
------------------------------------------------------------------------------------------------------
NOT IN示例:
--该例子想要返回没有下属的职员的姓名,如果子查询中有空值返回的话,则整个查询将没有结果返回
11:20:02SYS@test3>connscott/tigerConnected.11:21:18SCOTT@test3>select*fromemp;EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNO----------------------------------------------------------------------------------------7369SMITHCLERK79021980-12-1700:00:00800207499ALLENSALESMAN76981981-02-2000:00:001600300307521WARDSALESMAN76981981-02-2200:00:001250500307566JONESMANAGER78391981-04-0200:00:002975207654MARTINSALESMAN76981981-09-2800:00:0012501400307698BLAKEMANAGER78391981-05-0100:00:002850307782CLARKMANAGER78391981-06-0900:00:002450107788SCOTTANALYST75661987-04-1900:00:003000207839KINGPRESIDENT1981-11-1700:00:005000107844TURNERSALESMAN76981981-09-0800:00:0015000307876ADAMSCLERK77881987-05-2300:00:001100207900JAMESCLERK76981981-12-0300:00:00950307902FORDANALYST75661981-12-0300:00:003000207934MILLERCLERK77821982-01-2300:00:0013001014rowsselected.11:20:11SCOTT@test3>selectempnofromemp11:20:212whereempnoNOTIN(selectmgrfromemp);norowsselected
说明:
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:
11:20:42SCOTT@test3>selectempnofromemp11:21:042whereempnoin(selectmgrfromemp);EMPNO----------7566769877827788783979026rowsselected.
---------------------------------------------------------------------------------------------------------
Alternatively, a WHERE clause can be included in the subquery to display all employees who do not
have any subordinates:
--使用 Not In 的话,要注意除掉子查询中将要返回的空值
11:27:01SCOTT@test3>selectempnofromemp11:27:122whereempnoNOTIN(selectmgrfromempWHEREMGRISNOTNULL);EMPNO----------784475217654749979347369787679008rowsselected.
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。