pgsql学习与总结

实现树形结构查询

--创建表
CREATE TABLE province(
id int4 NOT NULL,
pid int4 NOT NULL,
name VARCHAR(32) NOT NULL,
PRIMARY KEY (id) 
);
--插入数据
insert into province (ID, pid, NAME)values (1,0,'山东');
insert into province (ID, pid, NAME)values (2,1,'菏泽');
insert into province (ID, pid, NAME)values (3,1,'济南');
insert into province (ID, pid, NAME)values (4,1,'济宁');
insert into province (ID, pid, NAME)values (5,2,'成武');
insert into province (ID, pid, NAME)values (6,2,'巨野');
insert into province (ID, pid, NAME)values (7,2,'曹县');
insert into province (ID, pid, NAME)values (8,5,'田集');
insert into province (ID, pid, NAME)values (9,5,'南鲁');
insert into province (ID, pid, NAME)values (10,4,'金乡');
insert into province (ID, pid, NAME)values (11,4,'微山');

--查询语句
with RECURSIVE T(id,name,pid,path,depth)as(
select id,name,pid,array[id]as path,1 as depth
from province 
where id=1
union all
select b.id,b.name,b.pid,t.path|| b.id,t.depth+1 as depth
from province b
join T on b.pid=T.id
)
SELECT id,name,pid,path,depth from T
ORDER BY depth,id

查询结果
在这里插入图片描述

实现字段自增

字段自增的实现有两种方法:
	1:使用serial/bigserial自增类型实现字段自增。
	2:自定义序列实现自增(可以自定义增量)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值