– 子查询(重点)
– 简单理解,在查询语句中,还有一个查询语句。
– 子查询会在主查询之前先执行一次,将得到的结果当做是主查询的条件使用。
– 子查询也叫内部查询。
– 查询比 ALLEN 工资高的人
– 1)先获取 ALLEN 的工资
select sal from scott.emp where ename = ‘ALLEN’; – 2600
– 2)查找比 ALLEN 工资高的员工
select * from scott.emp where sal > 2600;
– 使用子查询方式优化,一步搞定
select * from scott.emp where sal >
(select sal from scott.emp where ename = ‘ALLEN’);
– 子查询中常用的几种运算方式:in、any、all
– in:与列表中的任一值相等。就是一个 = 号
– any:与子查询中返回的每一个值进行比较。
– > any 大于最小的
– < any 小于最大的
– all:与子查询中返回的所有值进行比较。
– > all 大于最大的
– < all 小于最小的
– in 包含:将所有部门中工资最少的找出来
select * from scott.emp where sal in
(select min(sal) from scott.emp group by deptno);
– any
– 大于最小的
select * from scott.emp where sal > any
(select min(sal) from scott.emp group by deptno);
– 小于最大的
– 是从分组的结果中,找到最大的值作为条件
– 10 1300, 20 1100, 30 950
– 此处最大值为 1300,查出来的值应该都要小于 1300
select * from scott.emp where sal < any
(select min(sal) from scott.emp group by deptno);
– all
– 大于 1300
select * from scott.emp where sal > all
(select min(sal) from scott.emp group by deptno);
– 小于 950
select * from scott.emp where sal < all
(select min(sal) from scott.emp group by deptno);