子查询EXISTS和IN的使用

1.掌握子查询in的使用

2.掌握子查询exists的使用

之前已经知道了运算符IN,它允许我们在WHERE子句中过滤某个字段的
多个值。

where子句使用in语法
select column_name from table_name where column_name in (value1,value2)

如果运算符IN后面的值是来源于某个查询结果,并非是指定的几个值,这时就需要用到子查询。
子查询又称为内部查询或嵌套查询,即在SQL查询的WHERE字句中嵌入查询语句。

要查询所有选修了计算机课程的学生信息,
我们所要的数据在学生表里面,但是限定条件在分数表里,
我们怎么做呢?
select 学号,姓名,地址
from 学生表
where 学号 in(select 学号from 成绩表 where 科目=‘计算机’);
在这里插入图片描述

子查询IN语法
select column_name from table_name
where column_name in
(
select column_name from table_name where condition
);

EXISTS是子查询中用于测试内部查询是否返回任何行的布尔运算符。
将主查询的数据放到子查询中做条件验证,根据验证结果(TRUE或FALSE)
来决定主查询的数据结果是否保留。

说明:在处理固定值的时候,in的效率比exists要高

exists其实就是取代了In的位置,where 子句使用exists,然后子查询写在其后的括号内。

select column_name
from table_name
where exists
(select * from table_name2 where condition);

导入表格

drop table if exists score;
drop table if exists student;

create table student(
	stu_no varchar(20) not null primary key comment '学号',
	name varchar(30) comment '姓名',
	address varchar(150) comment '地址'
);

insert into student(stu_no, name, address) values('2016001', '张三', '贵州贵阳');
insert into student(stu_no, name, address) values('2016002', '李芳', '陕西兴平');
insert into student(stu_no, name, address) values('2016003', '张晓燕', '江西南昌');

create table score(
	id int not null auto_increment primary key,
	course varchar(50) comment '科目',
	stu_no varchar(20) comment '学号',
	score int comment '分数',
	foreign key(stu_no) references student(stu_no)
);

insert into score(course, stu_no, score) values('计算机', '2016001', 99);
insert into score(course, stu_no, score) values('离散数学', '2016001', 85);
insert into score(course, stu_no, score) values('计算机', '2016002', 78);

先查看下表的状态
select * from score;
select * from student;
在这里插入图片描述

查询所有选修了课程的学生信息
mysql> select A.* from student A where A.stu_no in(select B.stu_no from score B);

思路:学生表记录了学生信息,包括学号,姓名和住址。
分数表则记录了所选修的课程及分数,两个表的学号字段是相同的,
若要选出选修课程学生的信息,则把【学生表的学号==分数表学号】的那部分
数据输出出来就可以了,只有相等才会返回数据。


查询有谁选修了课程离散数学
select A.* from student A where stu_no in
(
select B.stu_no  from score B where B.course='离散数学'
);

查询所有选修了课程的学生信息,使用exists
mysql> select A.* from student A where exists ( select B.stu_no from score  B where A.stu_no=B.stu_no  );

查询所有未选修课程的学生信息,使用exists
mysql> select A.* from student A where not exists ( select B.stu_no from score  B where A.stu_no=B.stu_no);
发布了82 篇原创文章 · 获赞 19 · 访问量 4635

猜你喜欢

转载自blog.csdn.net/ABCisCOOL/article/details/105300365