什么是子查询
有如下表,现要求编写sql语句,查看年龄比“李斯文”小的学生,要求显示这些学生的信息 ,红框中的学生是比李斯文年龄小的学生。
- 普通方法:
第一步:查询得到“李斯文”的出生日期
SELECT bornDate from student
where studentName="李斯文"
; ->1993-07-03
第二步:利用WHERE语句,筛选出生日期比“李斯文”大的学生
SELECT * from student
where bornDate >'1993-07-03'
;
- 子查询方法
将第二步需要的1993-07-03,用第一步中查询的语句代替,代码如下:
SELECT * from student
where bornDate >(SELECT bornDate from student
where studentName="李斯文")
;
where 嵌套子查询
简单版
- 找出比“孙权”大的人
select name,age from person
where age >
(
select age from person
where name = '孙权'
)
输出结果为
in嵌套查询
- 找出魏国的人
select name from person
where countryid in
(
select countryid from country
where countryname = '魏国'
)
输出结果为
some嵌套查询
- 语法
<表达式>{ =|<>|!=|>|>=|!>|<|<=|!<}some(子查询)
some在sql中的逻辑运算符号,如果在一系列比较中,有些值为True,那么结果就为True。
- 找出魏国的人
select name from person
where countryid = some --用等号和以下查询到的值比较,如果与其中一个相等,就返回
(
select countryid from country
where countryname = '魏国'
)
- 结果如下
all嵌套查询
- 语法
<表达式>{ =|<>|!=|>|>=|!>|<|<=|!<}all(子查询)
all是sql中的逻辑运算符好,如果一系列的比较都为true,那么结果才能为true。
- 返回大于“魏国”的id的人
select name from person
where countryid > all --当countryid大于以下返回的所有id,此结果才为True,此结果才返回
(
select countryid from country
where countryname = '魏国'
)
结果
exists嵌套查询
-
语法
exists 子查询
exists是sql中的逻辑运算符号。如果子查询有结果集返回,那么就为True。exists代表“存在”的意义,它只查找满足条件的那些记录。一旦找到第一个匹配的记录后,就马上停止查找。
但是如果子查询中因为加了条件而没有结果集返回,则主语句就不执行了:
SELECT * FROM Person
WHERE exists
(
SELECT * FROM Person
WHERE Person_Id = 100 --如果不存在Person_Id的记录,则子查询没有结果集返回,主语句不执行
)
参考:https://www.cnblogs.com/glassysky/p/11559082.html