简介
with as 相当于视图,是子查询的另一种写法,原理是将建立一个临时表。在做分析时如果需要多次使用到某些中间表可以使用该方法,格式如下:
with SQL_1 as (SELECT ***),SQL_2 as (SELECT ***)
select * from XXX where XXX and XXX;
例子
如对于EMP表:
SELECT * FROM EMP;
拆成两个表:
WITH
E_ID AS (SELECT EMPNO,ENAME FROM EMP),
DETAIL AS (SELECT EMPNO,JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP)
SELECT * FROM E_ID
同理:
WITH
E_ID AS (SELECT EMPNO,ENAME FROM EMP),
DETAIL AS (SELECT EMPNO,JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP)
SELECT * FROM DETAIL
直接使用视图:
WITH
E_ID AS (SELECT EMPNO,ENAME FROM EMP),
DETAIL AS (SELECT EMPNO,JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP)
SELECT * FROM e_id E JOIN DETAIL D ON E.EMPNO=D.EMPNO
可以多次使用,代替一些连接和嵌套,with as得到的信息存放到临时表中,减省数据库的资源从而提高性能