首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

exists的用法有关问题

2013-01-08 
exists的用法问题上面是emp表的数据select * from emp e1where exists (select * from emp e2 where e1.sa

exists的用法问题
exists的用法有关问题
上面是emp表的数据



select * 
from emp e1
where exists (select * from emp e2 where e1.sal = 950)


select * 
from emp e1
where exists (select * from emp e2 where e2.sal = 950)

前面两个查询语句的第一个为什么只放回一条记录,而第二个则全部返回,exists不是真就全部返回吗?我对此研究了3个钟头都一头雾水,求大神讲解一下吧..小女子谢过了..

[解决办法]
查询1的exists是依赖于主查询的,它为真时,当且仅当主查询的e1.sal = 950,而这个条件主查询只有一条记录

查询2的exists只要子查询的结果不为空,条件都成立,就会返回主查询的所有记录
[解决办法]
select * from tb1 with(nolock) where 查询条件 and exists(
  select '随便写,都无所谓' from tb2 where tb1.主键=tb2.主键 and 其他条件)

只要exists括号后面的成立(存在),也就在返回true,那么他就执行括号前面的一次,返回一个true,执行一次前面的,返回一个true,执行一次前面的。。。。。。
[解决办法]
第一个查询,exists的判断依赖主查询,结果集相当于select *  from  emp where sal = 950


第二个查询,exists判断子查询是否存在结果集,只要存在结果集,就返回所有主查询的结果集,结果集相当于select *  from  emp where 1=1 即where条件成立。

热点排行
Bad Request.