sql语句中exists用法举例

发布时间:2020-06-24编辑:脚本学堂
本文介绍了sql server中exists的用法,举几个exists语法的例子,有需要的朋友参考下。

问题:
查询学过编号为"01"并且也学过编号为"02"的课程的同学的信息
 

复制代码 代码示例:
--方法1
select student.* from student , sc where student.s# = sc.s# and sc.c# = '01' and exists (select 1 from sc sc_2 where sc_2.s# = sc.s# and sc_2.c# = '02') order by student.s# 
 

exists用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回值true或false。
 
例表a:tablein
<a href=http://www.jb200.com/db/sqlyuju/ target=_blank class=infotextkey>sql语句</a>exists用法1

例表b:tableex
sql语句exists用法2 
二). 比较使用 exists 和 in 的查询。注意两个查询返回相同的结果。
 

复制代码 代码示例:
select * from tablein where exists(select bid from tableex where bname=tablein.aname)
select * from tablein where aname in(select bname from tableex)
 

sql语句exists用法3

三). 比较使用 exists 和 = any 的查询。注意两个查询返回相同的结果。
 

复制代码 代码示例:
select * from tablein where exists(select bid from tableex where bname=tablein.aname)
select * from tablein where aname=any(select bname from tableex)

sql语句exists用法4

not exists 的作用与 exists 正好相反。如果子查询没有返回行,则满足了 not exists 中的 where 子句。
 
一种通俗的可以理解为:将外查询表的每一行,代入内查询作为检验,如果内查询返回的结果取非空值,则exists子句返回true,这一行行可作为外查询的结果行,否则不能作为结果。
 
exists与in的使用效率的问题,通常情况下采用exists要比in效率高,因为in不走索引,但要看实际情况具体使用:
in适合于外表大而内表小的情况;exists适合于外表小而内表大的情况。