操作符 | 含义 |
---|---|
= | Equal to |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
<> | Not equal to |
示例1:
select ename,job,sal
from emp
where job=
(select job
from emp
where empno=7566) and sal >
(select sal
from emp
where empno=7782);
select ename,job,sal
from emp
where sal=
(select min(sal)
from emp);
select deptno,min(sal)
from emp
group by deptno
having min(sal) >
(select min(sal)
from emp
where deptno=20);
示例4:
查询出比雇员7654的工资高,同时从事和7788的工作一样的员工
select *
from emp t1
where t1.sal>
(select t.sal
from emp t
where t.empno=7654) and t1.job=
(select t2.job
from emp t2
where t2.empno=7654);
示例5:
要求查询每个部门的最低工资和最低工资的雇员和部门名称
select d.dname, a.minsal, e.ename
from dept d,
(select deptno, min(sal) minsal
from emp
group by deptno) a,emp e
where d.deptno=a.deptno and e.sal=a.minsal;
select empno,ename
from emp
where sal=
(select min(sal)
from emp
group by deptno);
操作符 | 含义 |
---|---|
IN | 等于列表中的任何一个 |
ANY | 和子查询返回的任意一个值比较 |
ALL | 和子查询返回的所有值比较 |
示例:in 在集合中
查询部门名称是SALES和ACOUNTING的员工
select * from emp where deptno in
(select deptno from dept where dname='SALES' or dname='ACCOUNTING');
示例:any 和集合中的任意一个值比较
查询工资比30号部门员工高的员工信息
select * from emp where sal > any
(select sal from emp where deptno=30);
示例:all 和集合中的所有值比较
查询工资比30号部门所有员工高的员工信息
select * from emp where sal > all
(select sal from emp where deptno=30);
示例:在select语句后使用子查询
注意:select语句后的子查询必须是单行子查询
查询员工号,姓名,薪水,7839的职位
select empno,ename,sal,
(select job
from emp
where empno=7839)
from emp;
示例:在from语句后面使用子查询
查询员工信息:员工号,姓名,月薪
select *
from (select empno, ename, sal from emp);
查询员工表中工资最高的前三名
select rownum, empno, ename, sal
from (select * from emp order by sal desc)
where rownum <= 3;
select e.empno, e.ename, e.sal, d.avgsal
from emp e, (select deptno, avg(sal) avgsal from emp group by deptno) d
where e. deptno=d.deptno and e.sal > d.avgsal;
相关子查询:
将主查询中的值 作为参数传递给子查询
使用相关子查询解决上面的示例
select empno, ename, sal, (select avg(sal) from emp where deptno=e.deptno) avgsal
from emp e
where sal > (select avg(sal) from emp where deptno=e.deptno);
示例:统计每年入职员工的个数
select count(*) Total,
sum(decode(to_char(hiredate, 'yyyy'), '1980', 1, 0)) "1980",
sum(decode(to_char(hiredate, 'yyyy'), '1981', 1, 0)) "1981",
sum(decode(to_char(hiredate, 'yyyy'), '1982', 1, 0)) "1982",
sum(decode(to_char(hiredate, 'yyyy'), '1987', 1, 0)) "1987"
from emp;