Oracle 多表查询

SQL> /*

SQL> 外连接:某些不成立的记录,通过外连接依然可以包含在最后的结果中

SQL> 左外连接:当where e.deptno=d.deptno不成立的时候,等号左边的表仍然包含在最后的结果中

SQL> 写法:where e.deptno=d.deptno(+)

SQL> 右外连接:当where e.deptno=d.deptno不成立的时候,等号右边的表仍然包含在最后的结果中

SQL> 写法: where e.deptno(+)=d.deptno

SQL> */

SQL> select d.deptno 部门号,d.dname 部门名称,count(e.empno) 人数

from emp e,dept d

where e.deptno(+)=d.deptno

group by d.deptno,d.dname;

部门号 部门名称 人数

---------- -------------- ----------

10 ACCOUNTING 3

40 OPERATIONS 0

20 RESEARCH 5

30 SALES 6

 

SQL> --自连接:通过表的别名,将同一张表视为多张表

SQL> select e.ename 员工的名字,b.ename 老板名字

2 from emp e,emp b

3 where e.mgr=b.empno;

员工的名字 老板名字

---------- ----------

FORD JONES

SCOTT JONES

JAMES BLAKE

TURNER BLAKE

MARTIN BLAKE

 

SQL> -- 两张表连接 利用笛卡尔积 count(*) = count(*) * count(d)

SQL> select count(*) from emp e,dept d;

COUNT(*)

----------

56

 

 

Oracle 多表查询

 

SQL> --自连接:不适合操作大表

SQL> --层次查询 有level属性

SQL> select level,empno,ename,mgr

from emp

connect by prior empno = mgr

start with mgr is null

order by 1;

 

LEVEL EMPNO ENAME MGR

---------- ---------- ---------- ----------

1 7839 KING

2 7566 JONES 7839

2 7698 BLAKE 7839

2 7782 CLARK 7839

3 7902 FORD 7566

3 7521 WARD 7698

3 7900 JAMES 7698

3 7934 MILLER 7782

3 7499 ALLEN 7698

3 7788 SCOTT 7566

3 7654 MARTIN 7698

 

LEVEL EMPNO ENAME MGR

---------- ---------- ---------- ----------

3 7844 TURNER 7698

4 7876 ADAMS 7788

4 7369 SMITH 7902

 

已选择 14 行。

 

SQL> /*

SQL> 第一层: start with mgr is null

SQL> 第二层: where mgr= 7839---> (7566,****,***)

SQL> 第三层: where mgr in (7566,****,***)

SQL> */