1. 子查询和主查询基本知识
1.1 子查询
在一个 select 语句中,嵌入了另外一个 select 语句, 那么被嵌入的 select 语句称之为子查询语
句
1.2 主查询
主要查询的对象,第一条 select 语句
1.3 主查询和子查询的关系
- 子查询是嵌入到主查询中
- 子查询是辅助主查询的,要么充当条件,要么充当数据源
- 子查询是可以独立存在的语句,是一条完整的 select 语句
查询班级学生平均年龄
select avg(age) from students
-- 查询班级学生平均年龄
-- select avg(age) from students
select * FROM students where age >21.5833
一条语句搞定
select * from students where age>(select avg(age) from students)
查询年龄最小的人
select name from students where age = (select min(age) from students)
例2:查询王昭君的成绩,要求显示成绩学生表中查询王昭君的学号
select score from scores where studentNo = (select studentNo from students where name = '王昭君')
例3:查询王昭君的数据库成绩并显示成绩
SELECT
*
FROM scores
WHERE
studentNo=(SELECT studentNo FROM students where name='王昭君')
and
courseNo=(SELECT courseNo FROM courses WHERE name='数据库')