前言
本文只是通过一个例子,得到我对SQL中exists的一个简单理解,所以很短,有错误,望告知(●’◡’●)!
主体
用到的两张表:
sc表:
sno | cno | grade |
---|---|---|
201215121 | 1 | 92 |
201215121 | 2 | 85 |
201215121 | 3 | 88 |
201215122 | 2 | 90 |
201215122 | 3 | 80 |
student表:
sno | sname | ssex | sage |
---|---|---|---|
201215121 | 李勇 | 男 | 20 |
201215122 | 刘晨 | 女 | 19 |
201215123 | 王敏 | 女 | 18 |
201215124 | 张立 | 男 | 19 |
需求:
筛选出选择了课程号为2的学生姓名(即cno=2)
上代码:
select sname
from student
where exists(
select * from sc
where cno=2 and sc.sno=student.sno
)
分析执行过程:
1.从student表中的第一行数据开始,把数据中的sno传递给内查询(因为内查询中需要该数据,内查询指括号里面的select语句)
2.则此时内查询语句相当于变为
select * from sc
where cno=2 and sc.sno='201215121'
3.若第二步中的查询语句查询到的结果不为空,则内查询返回ture,并将该行数据保存到结果集
4.对student表中每条数据由上到下进行以上步骤,最后形成最终的结果集,并输出其中的sname
引申思考:
如果把上面代码变为:
select sname
from student
where exists(
select * from sc,student
where cno=2 and sc.sno=student.sno
)
相比较与上述代码,该代码只是增加了一个student,大家可以思考下最后输出结果会有什么不同呢?为什么会这样呢?(⊙_⊙)?