Oracle中子查询问题

[复制链接]
查看11 | 回复2 | 2011-3-19 06:19:20 | 显示全部楼层 |阅读模式
我要查询scott.emp表,查询其中不是领导的员工信息。在mgr字段中出现的是领导的empno。我对Oracle的子查询不太理解,请高手看看我下面的语句到底是什么问题。

SELECT * FROM emp WHERE empno NOT IN
(SELECT DISTINCT mgr FROM emp);
为什么这语句的查询结果为0行。
希望高手给出正确的答案!
回复

使用道具 举报

千问 | 2011-3-19 06:19:20 | 显示全部楼层
<pre id=\"best-answer-content\" class=\"reply-text mb10\">楼主是由于在MGR字段中出现NULL,具体原因请看参考资料。 下面是摘录:
not in语句实质上等同于使用=比较每一值,如果测试为false或null,结果为比较失败。例如:
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));
这些查询不会返回所有一行。第二个查询语句更为明显,即1 != null,所以整个where都为false。然而这些查询语句可变为:
select true from dual where 1 not in (2,3);
select true from dual where 1 != 2 and 1 != 3;
你也能使用not in查询,只要你确保返回的值不会出现null值:
selectename from emp where empno not in (select mgr from emp where mgr is not null);
selectename from emp where empno not in (select nvl(mgr,0) from emp);
通过理解in,exists, not in,及not exists之间的差别,当null出目前任一子查询中时,你能避免一些常见的问题。











参考资料:<span class=\"gray\"><a href=\"http://www.sudu.cn/info/article/articleInfo.php?aId=21145\" target=\"_blank\">http://www.sudu.cn/info/article/articleInfo.php?aId=21145</a></span>
回复

使用道具 举报

千问 | 2011-3-19 06:19:20 | 显示全部楼层
<pre class=\"replyask-text\" id=\"content-2019489\">你是在回答我的问题吗?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行