
所有的IN都可以转换为EXISTS,同样NOT IN可以转换为NOT EXISTS,下面说明IN转换为EXISTS的方法,NOT的类似:
IN的语句:
SELECT * FROM A WHERE F IN (SELECT F FROM B)
可以转换为如下的EXISTS语句:
SELECT * FROM A WHERE EXISTS
(SELECT * FROM B WHERE A.F=B.F)
上面转换的说明:两个WHETE都可能有更多都条件,那么直接AND在相应的地方即可。另外表A和B的关联字段可能名字表同,也司没关系的。
我重写一下你的语句你应该就明白了select count(*) from customer_info as c
where c.custcd not in (
select c.custcd from grade_model_info where '10000'=c.custcd
)
sqlserver是支持这样的写法的,如果是外部表的条件尽量写在外部
而且内部select列不要出现外部表名,可以用表别名加以区分,如
select g.custcd from grade_model_info as g where '10000'=g.custcd
这样运行时就会提示错误了
我给你举几个例子你感受一下。
(1)select * from student where class not in ('1','2','3')
查询班级不在1,2,3的学生信息
(2))select * from student where class in ('1','2','3')
查询班级在1,2,3的学生信息
in和not in的用法,更多会出现在子查询中,
例如 select * from student where sno in (select sno from Exam where course ='English') 查询参加了英语考试的学生信息。
(3)exists 更多时候出现在if判断中, 它只做一个是或否的判断,例如如果存在birthday=今天的学生,那么就把他的age+1
if exists (select 1 from student where birthday=getdate())BEGIN
update student set age=age+1 where birthday=getdate()
END
else
select N'今天没有同学过生日'
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)