SELECT select_list
FROM table
WHERE expr operator
( SELECT select_list
FROM table);
SELECT ename
FROM emp
WHERE sal >
( SELECT sal
FROM emp
WHERE ename='JONES');
ENAME |
KING |
FORD |
SCOTT |
根据子查询返回的行数量,分为:
运算符 |
含义 |
= |
等于 |
> |
大于 |
>= |
大于等于 |
< |
小于 |
<= |
小于等于 |
<> |
不等于 |
SELECT ename, job
FROM emp
WHERE job =
(SELECT job FROM emp WHERE empno = 7369)
AND sal >
(SELECT sal FROM emp WHERE empno = 7876);
ENAME |
JOB |
MILLER |
CLERK |
SELECT ename, job, sal
FROM emp
WHERE sal = (SELECT MIN(sal) FROM emp);
ENAME |
JOB |
SAL |
SMITH |
CLERK |
800 |
SELECT deptno, MIN(sal)
FROM emp
GROUP BY deptno
HAVING MIN(sal) >
(SELECT MIN(sal)
FROM emp
WHERE deptno = 20);
SELECT ename, sal
FROM emp
WHERE empno IN (SELECT mgr
FROM emp);
ENAME |
SAL |
SCOTT |
3000.00 |
KING |
5000.00 |
JONES |
2975.00 |
FORD |
3000.00 |
CLARK |
2450.00 |
BLAKE |
2850.00 |
SELECT ename, sal
FROM emp
WHERE empno = ANY (SELECT mgr
FROM emp);
ENAME |
SAL |
JONES |
2975.00 |
BLAKE |
2850.00 |
CLARK |
2450.00 |
SCOTT |
3000.00 |
KING |
5000.00 |
FORD |
3000.00 |
SELECT empno, ename, job, sal
FROM emp
WHERE sal > ANY (SELECT sal
FROM emp
WHERE deptno = 10)
AND deptno <> 10;
EMPNO |
ENAME |
JOB |
SAL |
7499 |
ALLEN |
SALESMAN |
1600.00 |
7566 |
JONES |
MANAGER |
2975.00 |
7698 |
BLAKE |
MANAGER |
2850.00 |
7788 |
SCOTT |
ANALYST |
3000.00 |
7844 |
TURNER |
SALESMAN |
1500.00 |
7902 |
FORD |
ANALYST |
3000.00 |
SELECT empno, ename,job, sal
FROM emp
WHERE sal > ALL (SELECT sal
FROM emp
WHERE deptno= 20)
AND deptno <> 20;
EMPNO |
ENAME |
JOB |
SAL |
7839 |
KING |
PRESIDENT |
5000.00 |
SELECT empno, ename,job, sal
FROM emp
WHERE sal < ALL (SELECT sal
FROM emp
WHERE deptno= 10)
AND deptno <> 10;
EMPNO |
ENAME |
JOB |
SAL |
7369 |
SMITH |
CLERK |
800.00 |
7521 |
WARD |
SALESMAN |
1250.00 |
7654 |
MARTIN |
SALESMAN |
1250.00 |
7876 |
ADAMS |
CLERK |
1100.00 |
7900 |
JAMES |
CLERK |
950.00 |
除了常用单行子查询和多行子查询外,还有特殊情况使用的多列子查询,此部分内容大家了解即可,以便于后续在笔试中遇见此类问题可以及时解决。
例:查询每个部门入职时间最早的部门编号,员工姓名,入职时间
SELECT deptno,ename,hiredate
FROM emp
WHERE (deptno,hiredate) IN (SELECT deptno ,MIN(hiredate)
FROM emp
GROUP BY deptno);
查询结果为
DEPTNO |
ENAME |
HIREDATE |
20 |
SMITH |
1980-12-17 |
30 |
ALLEN |
1981-02-20 |
10 |
CLARK |
1981-06-09 |
SELECT ename
FROM emp
WHERE empno NOT IN
(SELECT mgr
FROM emp);
ENAME |
SELECT a.ename, a.sal, a.deptno, b.salavg
FROM emp a, (SELECT deptno, AVG(sal) salavg
FROM emp
GROUP BY deptno) b
WHERE a.deptno = b.deptno AND a.sal > b.salavg;
ENAME |
SAL |
DEPTNO |
SALAVG |
KING |
5000.00 |
10 |
2916.666667 |
JONES |
2975.00 |
20 |
2175.000000 |
SCOTT |
3000.00 |
20 |
2175.000000 |
FORD |
3000.00 |
20 |
2175.000000 |
ALLEN |
1600.00 |
30 |
1566.666667 |
BLAKE |
2850.00 |
30 |
1566.666667 |