SQL语句——11、子查询

子查询指嵌入在其他SQL中的select语句,也称嵌套查询.

按照子查询返回结果,可将子查询分为:

  • 单行单列
  • 单行多列
  • 多行单列
  • 多行多列

特点:

  1. 优先执行子查询,主查询再使用子查询的结果
  2. 子查询返回的列数和类型要匹配
  3. 子查询要用括号括起来
  4. 子查询返回多行要用多行关系运算符

单行子查询

子查询返回一行记录。
例如:查询和scott在同一部门的员工

select deptno,ename,sal from emp where deptno=(select deptno from emp where ename='SCOTT');

DEPTNO ENAME SAL
---------- ---------- ----------
20 SMITH 800
20 JONES 2975
20 SCOTT 3000
20 ADAMS 1100
20 FORD 3000

也可以把子查询结果当成一列

 select deptno,ename,(select deptno from emp where ename='SCOTT') AA from emp where deptno=10;

DEPTNO ENAME AA
---------- ---------- ----------
10 CLARK 20
10 KING 20
10 MILLER 20

多行子查询

多行子查询指返回多行数据的子查询语句。当在where中使用时,必须使用多行比较符(in all any)。

ALL和any操作符不能独立使用,要与单行比较符(= > < >= <= <>)结合使用。

  • in 匹配于子查询结果的任一个值即可
  • ALL 必须要符合子查询结果的所有值
  • ANY 只要符合子查询结果的任意一个值即可

in 操作

select empno,ename,sal from emp where empno in (select empno from emp where deptno=10);

EMPNO ENAME SAL
---------- ---------- ----------
7782 CLARK 2450
7839 KING 5000
7934 MILLER 1300

或者,查找每个部门的最高工资的员工姓名

select deptno,ename,sal from emp where (deptno,sal) in (select deptno,max(sal) from emp group by deptno);

DEPTNO ENAME SAL
---------- ---------- ----------
30 BLAKE 2850
20 SCOTT 3000
10 KING 5000
20 FORD 3000

any 操作

小于最大的即可

select deptno,ename,sal from emp where deptno < any (select distinct deptno from emp where deptno = 20 or deptno = 30);

DEPTNO ENAME SAL
---------- ---------- ----------
10 CLARK 2450
10 KING 5000
10 MILLER 1300
20 JONES 2975
20 FORD 3000
20 ADAMS 1100
20 SMITH 800
20 SCOTT 3000

8 rows selected.

ALL 操作

小于最小的即可

select deptno,ename,sal from emp where deptno < all (select distinct deptno from emp where deptno = 20 or deptno = 30);

DEPTNO ENAME SAL
---------- ---------- ----------
10 CLARK 2450
10 KING 5000
10 MILLER 1300

多列子查询

指子查询返回多个列的数据。当多个列只有一行数据时,可以使用单行比较符;当多个列有多行数据时,还是需要 IN,ALL ANY 实际中已经不实用了

多个列只有一行数据,例如:查询和SMITH相同部门相同岗位的人

select deptno,ename,job,sal from emp where (deptno,job) = (select deptno,job from emp where ename='SMITH');

DEPTNO ENAME JOB SAL
---------- ---------- --------- ----------
20 SMITH CLERK 800
20 ADAMS CLERK 1100

IN举例:找出领导和工资与SCOTT和WARD一致的人

select deptno,ename,mgr,sal from emp where (mgr,sal) in (select mgr,sal from emp where ename in ('SCOTT','WARD')) and ename not in ('SCOTT','WARD');

关联子查询

将主查询的内容传递给子查询,子查询再把查询结构反馈给主查询。子查询执行的次数取决于主查询传递值的次数

例如:找出每个部门工资最高的人

不使用关联子查询,使用in分组方式实现

SQL> select deptno,ename,sal from emp where sal in (select max(sal) from emp group by deptno);

DEPTNO ENAME SAL
---------- ---------- ----------
30 BLAKE 2850
20 SCOTT 3000
10 KING 5000
20 FORD 3000

关联子查询方式

SQL> select deptno,ename,sal from emp e where sal = (select max(sal) from emp where deptno=e.deptno);

DEPTNO ENAME SAL
---------- ---------- ----------
30 BLAKE 2850
20 SCOTT 3000
10 KING 5000
20 FORD 3000

猜你喜欢

转载自www.cnblogs.com/marxist/p/12149350.html