In PostgreSQL, the WITH clause provides a way to write the auxiliary reports and queries used in a large query. It helps break down complex and large queries in a simple and easy-to-read form.
1. Build a table
[SQL]View PlainCopy
- postgres=# Create table tb9 (ID serial primary key,name character varying, parentid Integer);
- CREATE TABLE
[SQL]View PlainCopy
- postgres=# \d TB9
- Table "public.tb9"
- Column | Type | Modifiers
- ----------+-------------------+--------------------------------------------------
- ID | Integer | Not null default Nextval (' tb9_id_seq ':: regclass)
- name | Character Varying |
- ParentID | Integer |
- Indexes:
- "Tb9_pkey" PRIMARY KEY, btree (ID)
2. Inserting test data
[SQL]View PlainCopy
- postgres=# INSERT INTO tb9 values (generate_series (1,5),' John ', 0);
- INSERT 0 5
- postgres=# INSERT INTO tb9 values (6,' john1 ', 1);
- INSERT 0 1
- postgres=# INSERT INTO tb9 values (7,' John2 ', 1);
- INSERT 0 1
- postgres=# INSERT INTO tb9 values (8,' John11 ', 6);
- INSERT 0 1
[SQL]View PlainCopy
- postgres=# SELECT * from tb9;
- ID | name | ParentID
- ----+--------+----------
- 1 | John | 0
- 2 | John | 0
- 3 | John | 0
- 4 | John | 0
- 5 | John | 0
- 6 | john1 | 1
- 7 | john2 | 1
- 8 | John11 | 6
- (8 rows)
3. With clause
[SQL]View PlainCopy
- postgres=# with t as (select * from tb9 where parentid=1) select count (0) from t;
- Count
- -------
- 2
- (1 row)
[SQL]View PlainCopy
- postgres=# with t (a,b,c) as (select * from tb9 where parentid=1) select a,b,c from t;
- A | B | C
- ---+-------+---
- 6 | john1 | 1
- 7 | john2 | 1
- (2 rows)
4. Combined use of multiple with clauses
Parentid=1 all child records of the record
[SQL]View PlainCopy
- postgres=# with t1 as (select * from tb9), T2 as (select * from tb9 where parentid=1) select t1.* from t1,t2 WHERE T2.ID=T1.PARENTID;  
- id | name | parentid
- - ---+--------+----------
- 8 | john11 | 6
- (1 row)
5. Recursion
All child records for records with ID 1
[SQL]View PlainCopy
- postgres=# with recursive T as (select ID,name,parentid from tb9 where id=1 UNION ALL select k.id,k. name,k.parentid from tb9 k,t where T.id=k.parentid) select * from t;
- ID | name | ParentID
- ----+--------+----------
- 1 | John | 0
- 6 | john1 | 1
- 7 | john2 | 1
- 8 | John11 | 6
- 9 | John21 | 7
- (5 rows)
Transfer from http://blog.csdn.net/luojinbai/article/details/44015581
PostgreSQL with recursion