0


SQL Server中的EXISTS语法

    在SQL Server相关子查询中,难免会用到EXISTS。那么,EXISTS 与 IN 有什么区别呢?

我们先聊一聊 EXISTS 的应用场景。

  **  IN :主要用于不相关子查询中,即子查询可以单独运行。**

    **EXISTS:多用与不相关子查询中,当然相关子查询也可以使用**

我们通过代码展示:

IN的例子:

--查询所有70分以上的学生姓名

--查询所有70分以上的学生姓名
select stu_name from student where stu_id not in 
    (select stu_id from StudentGrade 
    where Grade <70 or grade= Null)
    可以看出括号内的子查询语句是一个完整的查询语句,其运行顺序是先运行子查询,在运行父查询。

也可以写成:

--查询所有70分以上的学生姓名
select stu_name from student where exists 
    (select stu_id from StudentGrade 
    where Grade >=70 or grade= Null AND student.stu_id = StudentGrade.stu_id )

EXISTS的经典例子:

--查询选出所有课程的同学

--查询选出所有课程的同学
select *
from student
where not exists(
    select *
    from Course
    where not exists(select*
        from studentgrade
        where StudentGrade.stu_id=student.Stu_id and
            StudentGrade.Course_id=c.Course_id
        )        
)
    在这里,子查询调用到父查询中的表,子查询语句不能单独运行的,这段代码怎么理解呢?

这里可以理解成编程语言的多重循环遍历:

    **1.打开Student表格,并查看第一元组(第一行)数据**

** 2.打开Course表格,并查看第一元组(第一行)数据**

** 3.打开StudentGrade表格,并查看第一、第二、第三......元组数据,直到结束,如果出现StudentGrade.stu_id=student.Stu_id 和 StudentGrade.Course_id=c.Course_id 则在末端子查询中返回True。**

    由此,用Python语言描述可以这么写(程序仅为帮助理解用,与实际查询有所不同)
def select():
    for i in Student:
        for j in Course:
            for k in StudentGrade:
                if i == k and j == k:
                    print(f“找到该学生为{i}”)
    由于外面两层NOT EXISITS ,可以理解为“双重否定变肯定”,即“Student不存在有课程没有选的”。

总结:EXISTS 比 IN 使用范围更广,即EXISTS可以代替IN,而IN不能代替EXIST。在相关子查询中,先运行子查询,在不相关子查询中,程序是由外向内依次运行。

标签: 数据库

本文转载自: https://blog.csdn.net/xms_123456/article/details/134770672
版权归原作者 xms_123456 所有, 如有侵权,请联系我们删除。

“SQL Server中的EXISTS语法”的评论:

还没有评论