一.标量子查询
子查询返回单个数值(数字,字符串,日期等),最简单的形式。
举例:如一张员工表一张部门表,通过部门ID关联,查出销售部的员工信息。
首先可以拆分成两部分,先获取部门ID,再查找对应的员工信息。
select id from dept where dept_name=’销售部';//结果id=4
select * from emp where dept_id=4;
然后我们来看子查询,将上一条语句直接插入下一条。
select * from emp where dept_id=(select id from dept where dept_name=’销售部’);
这就是一个简单标量子查询
二.列子查询
子查询返回的值是一列的属性(可以是多行),常用in ,not in,some和any(两者基本用法一致),all等连接。
举例:查询部门为销售部和市场部的员工信息。
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
查询比财务部所有员工工资都高的员工信息(聚合函数不能在where后面使用,换成group by和having)。
select * from emp where salary >all (select salary from emp where dept_id=(select id from dept where name = '财务部‘));
查询比财务部任意员工工资都高的员工信息
select * from emp where salary >any (select salary from emp where dept_id=(select id from dept where name = '财务部‘));
三.行子查询
子查询返回的数据是一行(可以是多列),常用=,<>,in,not in
举例:查询与liust薪资和领导相同的员工信息
select * from emp where (salary ,managerId)=(select salary ,managerId where name= 'liust');
四.表子查询
子查询返回的数据是一张表
举例:查询与liust或songyq薪资职位相同的员工信息。
select * from emp where (salary,job) in (select salary,job from emp where name='liust' or name = 'songyq');