Use with as SQL optimization

When we write some of the structure is relatively complex SQL statements, query the presence of a child may be reused in multiple places multiple levels, this time we can use  with as  statement of its independence, which greatly improve the readability of SQL, simplify SQL ~

with as also called sub-query part, first define a sql fragment, the sql fragment will be used throughout the sql statement sql statement in order to allow readability higher, as part of providing the data, and are often used in the collection of union, etc. operation.

with as it is similar to a temporary table or view can be used to store part of the sql statement as an alias, except that with as part of a one-off, and must be used in conjunction with other sql can !

Its greatest advantage is appropriate to improve the readability of the code, and if you want to repeatedly use with clause to the back, which can greatly simplify SQL; more important is: an analysis of multiple use, which is why the offer performance place, to "read less" objective.

WITH t1 AS (
        SELECT *
        FROM carinfo
    ), 
    t2 AS (
        SELECT *
        FROM car_blacklist
    )
SELECT *
FROM t1, t2

Note: This must be a sql query as a whole, can not add a semicolon after that it is with as statements, or will be error.

Precautions

1.  with clause must select statement quoted previously defined , at the same level with keywords can only be used once , more than only separated by commas ; the last one with between clauses and the following query can not have a comma, only by the right parenthesis split , with clauses of the query must be enclosed in parentheses.

The following wording will complain:

with t1 as (select * from carinfo)
with t2 as (select * from car_blacklist)
select * from t1,t2
with t1 as (select * from carinfo);
select * from t1

2. If you have defined with clause, but then there is no query with select, you will be given!

The following wording will complain:

with t1 as (select * from carinfo)

Correct wording (t1 is not used does not matter, there followed select the line):

with t1 as (select * from carinfo)
select * from carinfo

3. The front with clause query can be defined in a later with clause. But with a clause with clause can not be nested inside!

Correct wording:

with t1 as (select * from carinfo),
t2 as (select t1.id from t1)
select * from t2

 




Guess you like

Origin www.cnblogs.com/qfdy123/p/12200779.html