In与Exists的区别

    这两个函数是差不多的,但由于优化方案不同,通常NOT Exists要比NOT IN要快,因为NOT EXISTS可以使用结合算法二NOT IN就不行了,而EXISTS则不如IN快,因为这时候IN可能更多的使用结合算法。

    Select * from tableA Where exists(Select * From tableB Where tableB.ID=tableA.ID)

    这句相当于:Select * from tableA Where id in (Select ID From tableB)

    对于表tableA的每一条数据,都执行Select * From tableB Where tableB.ID=tableA.ID的存在性判断,如果表tableB中存在表tableA当前行相同的ID,则Exists为真,该行显示,否则不显示。

  • IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况
  • In确定给定的值是否与子查询或列表中的值相匹配
  • Exists指定一个子查询,检测行的存在

-----IN 和NOT IN-----

----哪些部门中有雇员工资大于?-----

 

select * from Department where Department.deptID=

(select FDeptID from Employee where Employee.empSalary>7000)

----报错信息如下:子查询返回的值多于一个........

----Msg 512, Level 16, State 1, Line 1

----Subquery returned more than 1 value. This is not permitted when the

----subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.---

 

----改正:将“=”改为“in”

select * from Department where Department.deptID in

(select FDeptID from Employee where Employee.empSalary>7000)

go

----not in

select * from Department where Department.deptID in

(select FDeptID from Employee where Employee.empSalary>7000)

go

 

-----EXISTS 和NOT EXISTS-----一般用于IF语句的存在检测

----工资改革,检查雇员工资,达到以上的,每人提高,否则每人提高-----

/*--采用EXISTS子查询,进行酌情提升--*/

select * from Employee

go

if exists (select * from Employee where empSalary>7000)

begin

    Print '有人工资达到,则每人提高,提高后工资为:'

    update Employee set empSalary=empSalary+300

    select * from Employee

end

else

begin

    Print '无人工资达到,则每人提高,提高后工资为:'

    update Employee set empSalary=empSalary+500

    select * from Employee

end

go

 

----IN和Exists---

Select distinct deptName from Department

where exists(select * from Employee where empGender=1)

go

 

Select distinct deptName from Department

where deptID in(select FDeptID from Employee where empGender=1)

go

 

----exists相当于存在量词:表示集合存在,也就是集合不为空只作用于一个集合。

----exists P表示P不为空时为真;not Exists P表示P为空时,为真。

----in表示一个标量和医院关系的关系。s In P表示当s与P中的某个值相等时为真;

----s not in P表示s与P中的每一个值都不相等时,为真。

posted @ 2011-05-16 15:56  eva.xiao  阅读(29030)  评论(3编辑  收藏  举报