PostgreSQL-选择具有级别的表的所有层次结构

时间:2018-09-09 09:13:49

标签: sql postgresql hierarchical-data recursive-query

此刻我有问题。 我有一个名为places的表,其结构如下:

  • id
  • parent_id
  • 名称

我想进行选择以拥有此表的所有层次结构。有一个数据示例:

(1, null, '123 Barclay St')
(2, 1, 'Floor 1')
(3, 1, 'Floor 2')
(4, 1, 'Floor 3')
(5, 2, 'Hall 1')
(6, 2, 'Room 1')
(7, 2, 'Room 2')
(8, 3, 'Room 3')
(9, null, '10 Thames St')

显然,表中的顺序不是此顺序。

所以我想通过我的SELECT(9行)获得此结果:

123 Barclay St
   Floor 1
      Hall 1
      Room 1
      Room 2
   Floor 2
      Room 3
   Floor 3
10 Thames St

不是这个结果(我已经知道如何获得):

10 Thames St
123 Barclay St
   Floor 1
   Floor 2
   Floor 3
      Hall 1
      Room 1
      Room 2
      Room 3

如果您能帮助我,我先谢谢您。

2 个答案:

答案 0 :(得分:1)

这是使用递归CTE的解决方案:

MVC

enter image description here

Demo

这里的基本思想是构建路径字符串,该字符串跟踪从每个节点返回其根的完整路径(该根由WITH RECURSIVE cte AS ( SELECT LPAD(id::text, 3, '0') AS marker, ' ' AS buffer, id, parent_id, name::text FROM yourTable t WHERE parent_id IS NULL FROM yourTable t WHERE parent_id IS NULL UNION ALL SELECT t2.marker || ':' || LPAD(t1.parent_id::text, 3, '0') || ':' || LPAD(t1.id::text, 3, '0') AS marker, t2.buffer || ' ', t1.id, t1.parent_id, t2.buffer || t1.name FROM yourTable t1 INNER JOIN cte t2 ON t1.parent_id = t2.id ) SELECT name FROM cte ORDER BY marker; parent_id的节点给定)。然后,我们只需在此路径上执行单个NULL即可生成您想要的订单。

答案 1 :(得分:1)

您尚未提供已经提出的查询。但是-据我所知,您需要递归树结构。

https://www.db-fiddle.com/f/og5HZDHBhBRmP1cDnqgCBB/1

library(tokenizers)

text <- "I am a bad coder with good logical skills"

names(which.max(sapply(Filter(function(x) nchar(x) %% 2 == 0, 
                          unlist(tokenize_words(text))), nchar)))

#[1] "skills" 

查询:

CREATE TABLE rooms (
  id INTEGER, parent_id INTEGER, name TEXT
);

INSERT INTO rooms VALUES
(1, null, '123 Barclay St'),
(2, 1, 'Floor 1'),
(3, 1, 'Floor 2'),
(4, 1, 'Floor 3'),
(5, 2, 'Hall 1'),
(6, 2, 'Room 1'),
(7, 2, 'Room 2'),
(8, 3, 'Room 3'),
(9, null, '10 Thames St');

https://www.postgresql.org/docs/current/static/queries-with.html

相关问题