使用树形顺序从表中选择行
我有女巫包含字段:id,parent_id,名称(等)
我想按照“树木旅行顺序”命令这张桌子。
id parent_id
1, 0
3, 1
5, 1
2, 0
8, 2
4, 0
9, 4
(......)
简单描述:生根节点,追加所有子节点,接下来的根节点追加子节点等。
根据你的描述,我假设你的意思是广度优先,这可以用WITH RECURSIVE查询(PostgreSQL 8.4+)轻松完成:
WITH RECURSIVE tree
AS
(
SELECT
node_name, id, parent_id, NULL::varchar AS parent_name
FROM foo
WHERE parent_id IS NULL
UNION
SELECT
node_name, f1.id, f1.parent_id, tree.node_name AS parent_name
FROM
tree
JOIN foo f1 ON f1.parent_id = tree.id
)
SELECT node_name, empno, parent_id, node_name FROM tree;
您也可以使用以下SQL使用深度优先顺序:
WITH RECURSIVE tree
AS
(
SELECT
node_name, id, parent_id, NULL::varchar AS parent_name, id::text AS path
FROM foo WHERE parent_id IS NULL
UNION
SELECT
node_name, f1.id, f1.parent_id, tree.node_name AS parent_name, tree.path || '-' || f1.id::text AS path
FROM
tree
JOIN foo f1 ON f1.parent_id = tree.id
)
SELECT node_name, empno, parent_id, node_name, path FROM tree ORDER BY path;
正如synergetic所注意到的,由Diogo Biazus提供的深度优先的解决方案不适用于具有不同数字位数的ID。
但是您可以使用此解决方案,它使用整数数组:
WITH RECURSIVE tree
AS
(
SELECT
node_name, id, parent_id, NULL::varchar AS parent_name, array[id] AS path
FROM foo WHERE parent_id IS NULL
UNION
SELECT
node_name, f1.id, f1.parent_id, tree.node_name AS parent_name, tree.path || f1.id AS path
FROM
tree
JOIN foo f1 ON f1.parent_id = tree.id
)
SELECT node_name, empno, parent_id, node_name, path FROM tree ORDER BY path;
您也可以使用优秀的LTree模块,但您需要稍微重新组织数据。
链接地址: http://www.djcxy.com/p/30463.html