目录
子查询
1.准备工作
2--创建表格
3--插入数据
2.where 子查询单列单个数据
格式
查询
3.where 子查询单列多个数据(in)
格式
查询
使用子查询
4.from 多行多数据
格式
查询
子查询
将select的查询的返回结果 当成另外一个selet语句的内容去使用。
子查询放在()里面
注意:把select当成一个函数,一个可以返回结果的函数。只是我们可以给他传递不同参数,获取不同的结果。
1.准备工作
2--创建表格
-- 创建表格CREATE table class (class_id INT PRIMARY KEY AUTO_INCREMENT,class_name VARCHAR(20) ); create table student (id INT PRIMARY KEY AUTO_INCREMENT;student_name VARCHAR(30),student_sex char(1),student_info VARCHAR(500),student_class_id int,-- 添加主键约束CONSTRAINT student_class_fk FOREIGN KEY(student_class_id) REFERENCES class(class_id) );
![]()
3--插入数据
-- 插入数据 insert into class VALUES (null, '一班'), (null, '二班'), (null, '三班') ;INSERT into student VALUES (null, '偷走晚霞的人', '男', '一个学生', 1), (null, '惜.己', '男', '一个学生', 2), (null, '小玖', '女', '一个学生', 1), (null, '张三', '男', '一个学生', 3), (null, '莉莉', '男', '一个学生', 1), (null, '雪夜', '男', '一个学生', 2), (null, '小明', '女', '一个学生', 1), (null, '小新', '男', '一个学生', 3) ;
2.where 子查询单列单个数据
前提返回的数据是 单列单个
格式
这里不一定是等号,还可以是其他的逻辑运算符号
select * from 表名2 where 表名2.需要对比的字段 = (select 字段 from 表名2 where 条件);
查询
假设我们不知道一班的id ,但是又想查询一班的学生信息.先通过class_name 查询 一班的id
# 通过名字查询 一班的id =1 select class_id from class where class_name = '一班';
最后通过 id去获取 一班的信息
# 通过名字查询 一班的id =1 select class_id from class where class_name = '一班';
这里可以使用内查询==》可以看到查询结果是一样的
只是替换了 第二条sql语句中 为 1 的地方。去掉第一sql中的;
-- 整合两个sqlSELECT * from student WHERE student_class_id = (select class_id from class where class_name = '一班') ;
3.where 子查询单列多个数据(in)
格式
select * from 表名2 where 表名2.需要对比的字段 in (select 字段 from 表名2 where 条件);
查询
假设我们不知道一班,三班的id ,但是又想查询一班,三班的学生信息.先通过class_name 查询 一班的id和三班的id
-- 查询一班三班的信息 select class.class_id FROM class where class_name in ('一班', '三班'); -- 获取到id 为1 , 3
通过id去查询
-- 使用id 去查询二班三班的学生 SELECT * from student where student_class_id in (1,3)
使用子查询
SELECT * from student where student_class_id in(select class.class_id FROM class where class_name in ('一班', '三班'));
可以看到只是替换了 1,3的部分。
感觉跟套娃差不多,只是使用一个select的语句的查询结果供另外一个select使用。
4.from 多行多数据
这个需要注意起别名
格式
# 查询学生表信息 SELECT * from (select * From student ) s where s.student_sex = '女';
查询
查询一班的女生子查询版
注:这个是使用当前表的查询的结果再次进行查询。(这个个人感觉不到意义)
# 查询学生表信息 SELECT * from (select * From student ) s where s.student_sex = '女';
查询一班二班男生的信息以及班级的信息
-- 查询 一班,二班,三班 男生的信息select * from class LEFT JOIN (SELECT * from student where student_sex = '男') bs on class.class_id = bs.student_class_id;