Oracle in with as usage zf

the role with as the sql statement is actually a lot of repetition with as used on the inside, an alias, followed by a query you can use it, so for large quantities of sql statement optimization plays a role , but clearly clear. with as phrases, also called sub-query part (subquery factoring), allows you to do a lot of things, define a SQL snippet, the SQL fragment will be used throughout the SQL statement. Sometimes, in order to make more readable some SQL statements, there may be in different parts of UNION ALL as part of providing the data. Particularly useful for UNION ALL. Because each part of the UNION ALL may be the same, but if each part to perform it again, then the cost is too high, it can be used with as a phrase, then just run it again. If with the phrase as defined in the table name was called twice more, the optimizer will automatically with data obtained as a phrase into a TEMP table, if only called once, it will not. The prompt will materialize is mandatory data with as in the phrase into a global temporary table. Many of the queries by this method can improve the speed .

grammar:

For an alias
with tmp as (select * from tb_name )

For multiple aliases
with
   tmp AS (the SELECT * from tb_name),
   TMP2 (the SELECT * from tb_name2) AS,
   tmp3 AS (the SELECT * from tb_name3),
   ...

example:

- the equivalent of e built a temporary table  

with e as (select * from scott.emp e where e.empno=7499)  

select * from e; 

- the equivalent of a built e, d temporary table  

with  

     e as (select * from scott.emp),  

     d as (select * from scott.dept)  

select * from e, d where e.deptno = d.deptno; 

Used in conjunction with UNION ALL

with  

    sql1 as (select to_char(a) s_name from test_tempa),  

    sql2 as (select to_char(b) s_name from test_tempb where not exists (select s_name from sql1 where rownum=1))  

select * from sql1  

union all  

select * from sql2  

union all  

select 'no records' from dual  

       where not exists (select s_name from sql1 where rownum=1)  

       and not exists (select s_name from sql2 where rownum=1); 

WITH advantage statement:

(1). SQL enhance readability. For example, a query such as take a meaningful name for a particular child with.

(2), with the sub-query is executed only once, and the results stored in the user temporary table space, you can reference several times to enhance performance.

Guess you like

Origin www.cnblogs.com/friendlysong/p/11165502.html