-- 嵌套查询(nested query)在查询中还有其他查询
-- 子查询出现在where条件中
-- 子查询只会返回单行单列得结果
create table students(
id int primary key auto_increment,
cid int not null,
name varchar(45) not null unique
);
insert into students(cid,name) values
(1,'小王'),(2,'小张'),(3,'小谈'),(1,'小文'),(1,'小石');
-- 查询和小王cid一样的所有人
select * from students where cid = (
select cid from students where name ='小王'
);
-- 这是上一个的意思,两个语句的行为和上一条一样
select cid from students where name = '小王';
select * from students where cid=1;-- 这里的1是上一条查询的结果
-- 错误的语句,返回的结果超过一列
select * from students where cid = (
select id,cid from students where name ='小王'
);
-- 错误的语句,返回的结果超过一行
select * from students where cid = (
select cid from students
);
-- 单行多列的情况
select *from students where (id,cid)=(
select 1,3
);
-- 另一种形式
select *from students where (id,name)=(
select cid,name from students where id=4
);
-- 多行单列
select name from students where id<3;
select * from students where name in(
select name from students where id <3
);
-- ALL比最大的大
select id from students where cid=1;
select * from studnets where id>ALL(
select id from students where cid = 1
);
-- 视为
select * from students where id>3;
-- ANY存在
-- 比其中一项大,也就是比最小的大
-- exists
-- 先执行外部查询得到一个结果集,然后遍历结果集中的每条记录,并且代入到内部查询中
create table course(
cid int primary key auto_increment,
name varchar(45) not null unique
);
insert into course (name) values ('语文'),('数学'),('英语'),('地理'),('政治'),('历史');
create table score(
sid int primary key auto_increment,
student varchar(45) not null,
cid int not null,
score int not null
);
insert into score(student,cid,score)values
('小红',1,98),('小红',2,98),('小红',3,98),('小红',4,98),('小红',5,98),('小红',6,98);
select * from score where not exists( -- 所有记录
select * from course where score.cid=course.cid and name='语文' -- 所有不是语文得成绩
)and student='小红'; -- 小红的不是语文的成绩
select * from score where student = '小红';
select * from
(select * from score where student = '小红')as 小红的成绩 -- 起别名,必须
where cid=3;
-- 合并查询union,会合并重复的结果
-- union all不会合并重复的值