postgresql with递归
Posted 何事西风悲画扇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了postgresql with递归相关的知识,希望对你有一定的参考价值。
在PostgreSQL里,with子句提供了一种方法写一个大的查询中使用的辅助报表与查询。它有助于打破复杂和大型查询简单易读的形式。
1. 建表- postgres=# create table tb9(id serial primary key,name character varying, parentid integer);
- CREATE TABLE
- 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)
- 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
- 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)
- postgres=# with t as (select * from tb9 where parentid=1) select count(0) from t;
- count
- -------
- 2
- (1 row)
- 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)
parentid=1的记录的所有子记录
- 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)
id为1的记录的所有子记录
- 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)
转自 http://blog.csdn.net/luojinbai/article/details/44015581
以上是关于postgresql with递归的主要内容,如果未能解决你的问题,请参考以下文章