(三)子查询

1.where和having语句中的子查询

(1)单行子查询

  • 只返回一条记录
  • 单行操作符

需求:查询01科目中大于01科目平均分的记录

select * from score t1 
where cid = 01 and  score > ( select round(avg(score))  from score where cid =01 )

需求:查询科目数比01学过的科目数多的学生的学号

select sid from score
group by sid
having count(cid) >(select round(count(cid)) from score where sid = 01)

(2)多行子查询

返回多条记录

多行操作符

(2.1)in 和 not in运算符

需求:查询(没)学过01科目的学生信息

select * from student
where sid in (select sid from score where cid =01 )

select * from student
where sid not in (select sid from score where cid =01 )

(2.2)exists 和 not exists

需求:查询(没)学过01和02这两门科目的学生学号

select sid from score t1 
where t1.cid = 01 exists (select 1 from score t2 where t2.cid = 02 and t2.sid = t1.sid )

exists:

  • 带有EXISTS谓词的子查询不返回任何数据,只产生逻辑真值“true”或逻辑假值“false”
  • 使用存在量词EXISTS后,若内层查询结果非空,则外层的WHERE子句返回真值否则返回假值
  • 由EXISTS引出的子查询,其目标列表达式通常都用*,因为带EXISTS的子查询只返回真值或假值
  • 给出列名无实际意义

3.from语句中的子查询

from 子句的子查询为多行子查询

需求:查询学过01学生的学号、姓名、科目、成绩,要求使用子查询

select * from (select t1.sid,sname,cid,score from student t1
inner join score t2 on t1.sid =t2.sid 
)
where cid =01

3.select 字句中的子查询

select中的子查询必须为单行子查询

需求:查询学生的的学号,科目,成绩,出生年月

select score.*
,(select sname   from student where student.sid=score.sid) sname
,(select sage   from student where student.sid=score.sid) sage  from score

score.*:代表score表中的所有字段

作者:郭佳豪  创建时间:2023-10-18 09:52
最后编辑:郭佳豪  更新时间:2023-10-18 17:31