当前位置:Gxlcms > 数据库问题 > sql-in/not in和exists/not exists的区别

sql-in/not in和exists/not exists的区别

时间:2021-07-01 10:21:17 帮助过:4人阅读

* 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指定一个子查询,检测行的存在

 

 

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

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

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中的每一个值都不相等时,为真。

 

sql-in/not in和exists/not exists的区别

标签:

人气教程排行