
·标量子查询
·列子查询
·行子查询
·表子查询

自查询返回的结果为单个值,最简单的形式,这种子查询的称为标量子查询。

- # 查询所有年龄比hom大的员工
- select * from emp where age>(select age from emp where name='hom');


基础表格emp和course,emp的type字段和course的id字段连接在一起:


- -- (1)in():符合括号中的所有元素
- # 查询course表中的技术部和科研部的编号
- select id from course where name='技术部' or name='科研部';
- # 查询emp表中的type=1和3的员工
- select * from emp where type in(1,3);
- # 根据emp和course两个表,查询技术部和科研部的员工
- select * from emp where type in(select id from course where name='技术部' or name='科研部');

- -- (2)all():满足子查询返回的所有结果
- # 查询所有销售部的人员年龄
- select id from course where name='销售部';
- -- 得到销售部的部门ID为4
- select age from emp where type=(select id from course where name='销售部');
- # 查询比销售部所有人年龄都高的员工信息
- select * from emp where age>all(select age from emp where type=(select id from course where name='销售部'));

- -- (3)any()/some():满足子查询返回的任意一个结果
- # 查询管理部的员工的部门ID
- select id from course where name='管理部';
- -- 得到管理部的员工的部门ID=2之后,输出所有管理部员工的年龄
- select age from emp where type=(select id from course where name='管理部');
- -- 查询比管理部任意一人年龄都高的员工信息
- select * from emp where age>any(select age from emp where type=(select id from course where name='管理部'));



当用户需要查询与jom的年龄和部门相同的员工时,需要先查询jom的年龄和jom和所属部门的id,再查寻符合age和type的员工。
- # 查询jom的年龄age和所属部门type
- select age, type from emp where name='jom';
- # 得到age=35,以及type=2,再查询与jom的年龄age和所属部门type相同的员工
- select * from emp where age=35 and type=2;
但使用行子查询,是需要使用如下语句即可:
- # 行子查询操作:
- select * from emp where (age,type)=(select age, type from emp where name='jom');

子查询返回的结果是多行多列,也就是一张表,这种子查询被称为表子查询。

查询与’jom‘、’kom’的所属部门和年龄相同的员工信息:
- -- 1、查询与’jom‘、’kom’的所属部门和年龄相同的员工信息
- # 第一步,查询jom和kom的所属部门和年龄
- select age,type from emp where name='jom' or name='kom';
- # 第二步,查询与jom和kom的所属部门和年龄相同的员工信息
- select * from emp where (age,type) in (select age,type from emp where name='jom' or name='kom');

查询sum在10006之后的员工信息,其部门所属部门信息:
- -- 2、查询sum在10006之后的员工信息,其部门所属部门信息
- # 第一步,查询sum在10006之后的员工信息
- select * from emp where sum>10006;
- # 第二步,将第一步子查询的结果(一张表)作为传入参数传入,查询该部分员工对应的部门信息
- select e.*,c.* from (select * from emp where sum>10006) as e left join course as c on e.type=c.id;
