pgsql中层次查询方法

与Oracle中的start with ... connect by..非常相似的功能,查询后显示目录层次结构的方法:

当然在SQL Server 2005之后有with的功能。

 

测试代码:

DROP TABLE IF EXISTS t1;
CREATE TABLE t1(id integer primary key,
name varchar(32),
parent integer);

INSERT INTO t1 VALUES(1, '中国', 0);
INSERT INTO t1 VALUES(2, '江苏', 1);
INSERT INTO t1 VALUES(3, '浙江', 1);
INSERT INTO t1 VALUES(4, '上海', 1);
INSERT INTO t1 VALUES(5, '南京', 2);
INSERT INTO t1 VALUES(6, '苏州', 2);
INSERT INTO t1 VALUES(7, '杭州', 3);
INSERT INTO t1 VALUES(8, '宁波', 3);
INSERT INTO t1 VALUES(9, '昆山', 6);
INSERT INTO t1 VALUES(10,'常熟', 6);
INSERT INTO t1 VALUES(11,'吴江', 6);

 

 

实现代码:

WITH RECURSIVE X AS(SELECT t1.*, t1.id::text AS path 
FROM t1
WHERE layer = 1
UNION ALL
SELECT t1.*, path ||'|' || t1.id
FROM t1 JOIN x
ON t1.parent = x.id)
SELECT * FROM x ORDER BY path;



WITH RECURSIVE r AS ( 
SELECT * FROM t1 WHERE id = 6
UNION ALL
SELECT t1.* FROM t1, r WHERE t1.parent = r.id
)
SELECT * FROM r ORDER BY id;

你可能感兴趣的:(sql)