Using Recursive Common table expressions to represent Tree structures
http://www.postgresonline.com/journal/archives/131-Using-Recursive-Common-table-expressions-to-represent-Tree-structures.html
Tree Problem and was based on PostgreSQL 7.4 technology.
We'll repeat the text here for completeness and demonstrate the PostgreSQL 8.4 that solves this and more efficiently.
Suppose you are tracking supplies and have a field called si_item and
another called si_parentid.
The parent keeps track of what subclass a supply item belongs to. E.g.
you have paper parent that has subclasses such as recycled,
non-recycled. When someone takes supplies, you want to return the fully
qualified name e.g. Paper->Recycled->20 Lb
Below is what the structure of your table looks like.
si_id int, si_parentid int, si_item. In your table are the following entries
si_id | si_parentid | si_item |
---|---|---|
1 | Paper | |
2 | 1 | Recycled |
3 | 2 | 20 lb |
4 | 2 | 40 lb |
5 | 1 | Non-Recycled |
6 | 5 | 20 lb |
7 | 5 | 40 lb |
8 | 5 | Scraps |
Solution
CREATE TABLE supplyitem(si_id integer PRIMARY KEY, si_parentid integer, si_item varchar(100));
--load up the table (multirow constructor introduced in 8.2)
INSERT INTO supplyitem(si_id,si_parentid, si_item)
VALUES (1, NULL, 'Paper'),
(2,1, 'Recycled'),
(3,2, '20 lb'),
(4,2, '40 lb'),
(5,1, 'Non-Recycled'),
(6,5, '20 lb'),
(7,5, '40 lb'),
(8,5, 'Scraps');
--Recursive query (introduced in 8.4 returns fully qualified name)
WITH RECURSIVE supplytree AS
(SELECT si_id, si_item, si_parentid, CAST(si_item As varchar(1000)) As si_item_fullname
FROM supplyitem
WHERE si_parentid IS NULL
UNION ALL
SELECT si.si_id,si.si_item,
si.si_parentid,
CAST(sp.si_item_fullname || '->' || si.si_item As varchar(1000)) As si_item_fullname
FROM supplyitem As si
INNER JOIN supplytree AS sp
ON (si.si_parentid = sp.si_id)
)
SELECT si_id, si_item_fullname
FROM supplytree
ORDER BY si_item_fullname;
Result looks like
si_id | si_item_fullname
------+-----------------------------
1 | Paper
5 | Paper->Non-Recycled
6 | Paper->Non-Recycled->20 lb
7 | Paper->Non-Recycled->40 lb
8 | Paper->Non-Recycled->Scraps
2 | Paper->Recycled
3 | Paper->Recycled->20 lb
4 | Paper->Recycled->40 lb
- Using HStore for Archiving
- Using wget directly from PostgreSQL using COPY FROM PROGRAM
- Saying Happy Valentine in PostGIS
- Foreign Data Wrap (FDW) Text Array, hstore, and Jagged Arrays
- Finding contiguous primary keys
- String Aggregation in PostgreSQL, SQL Server, and MySQL
- Using LTree to Represent and Query Hierarchy and Tree Structures
- Allocating People into Groups with SQL the Sequel
- PostgresQL 8.4: Common Table Expressions (CTE), performance improvement, precalculated functions revisited
This post was mentioned on Twitter by roblb: Using Recursive
Common table expressions to represent Tree structures: A very long time
ago, we wrote .. http://bit.ly/Flne3 #postgres
Tracked: Jan 04, 21:19
Tracked: Aug 20, 00:58
(Linear | Threaded)
A couple of observations:
* Unless the length 1000 has some significance, use TEXT instead of
VARCHAR(1000).
* It might well be both faster and more correct to push items into an array
and use array_to_string() in the outer SELECT, and it won't be subject to
sorting anomalies.
WITH RECURSIVE supplytree AS
(
SELECT
si_id,
si_item,
si_parentid,
ARRAY[si_item] AS si_item_array
FROM supplyitem
WHERE si_parentid IS NULL
UNION ALL
SELECT
si.si_id,si.si_item,
si.si_parentid,
sp.si_item_array || si.si_item As si_item_array
FROM
supplyitem As si
JOIN
supplytree AS sp
ON (si.si_parentid = sp.si_id)
)
SELECT
si_id,
array_to_string(si_item_array, '->') AS si_item_fullname
FROM supplytree
ORDER BY si_item_array;
http://www.postgresql.org/docs/current/static/ltree.html
I'am not saying than WITH RECURSIVE is bad .. just that, there are simpler solution sometimes ;-)
will have to give it a test drive sometime. I think the only thing
against it is that its a PostgreSQL specific feature where as the CTE is
more ANSI portable (except for possiblyt the word RECURSIVE)
Couple of ways -- you could write a function as we demonstrated in
linked article, but that is not as suitable for multiple sets since it
would probably do a subquery for each record.
You coulde also take our example and limit with a WHERE clause but that is much slower than it could be.
The other way would be to recurse backward from the child to the parent.
So instead of starting at parent nodes -- you start at the child node
and keep on unioning until you hit a parent with no parent. Will have
to write that up sometime.
--Recursive query (introduced in 8.4 returns fully qualified name)
WITH RECURSIVE supplytree AS
(SELECT si_id, si_item, si_parentid, CAST(si_item As varchar(1000)) As si_item_fullname
FROM supplyitem
WHERE si_item in( '40 lb')
UNION ALL
SELECT si.si_id,si.si_item,
si.si_parentid,
CAST(si.si_item || '->' || sp.si_item_fullname As varchar(1000)) As si_item_fullname
FROM supplyitem As si
INNER JOIN supplytree AS sp
ON (si.si_id = sp.si_parentid)
)
SELECT si_id, si_item_fullname
FROM supplytree where si_parentid is null
ORDER BY si_item_fullname;
table tema
-field tema_id (is the identificator)
-field nombre (is the name)
-field padre_id (is the parent id)
WITH RECURSIVE tema_tree AS (
SELECT tema_id, nombre, padre_id, nombre||'' full_name
FROM tema
WHERE padre_id IS NULL
UNION ALL
SELECT t.tema_id, t.nombre, t.padre_id, tt.full_name||' -> '||t.nombre full_name
FROM tema t
JOIN tema_tree tt ON t.padre_id = tt.tema_id
)
SELECT tema_id, full_name
FROM tema_tree
ORDER BY 2
Using Recursive Common table expressions to represent Tree structures的更多相关文章
- PostgreSQL: WITH Queries (Common Table Expressions)
WITH 允许在 SELECT 语句中定义"表"的表达式,这个"表"的表达式称之为"公共表表达式(Common Table Expression)&q ...
- The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
https://stackoverflow.com/questions/30045871/sorting-the-view-based-on-frequency-in-sql-server Just ...
- Common Table Expressions (CTE)
子查询有时使用起来很麻烦,因为所有的过滤和匹配逻辑都必须集成到子查询表达式中.如果只需要执行一个任务,且只需要使用一次杳询表达式,子查询是很好的选择.但子查询不能被重用,也不能很好地支持多个需求.这个 ...
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 236. Lowest Common Ancestor of a Binary Tree
https://www.cnblogs.com/grandyang/p/4641968.html http://www.cnblogs.com/grandyang/p/4640572.html 利用二 ...
- 【LeetCode】236. Lowest Common Ancestor of a Binary Tree
Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) o ...
- CTE(Common Table Expression) 公用表表达式
在编写T-SQL代码时,往往需要临时存储某些结果集.前面我们已经广泛使用和介绍了两种临时存储结果集的方法:临时表和表变量.除此之外,还可以 使用公用表表达式的方法.公用表表达式(Common Tabl ...
- Leetcode之236. Lowest Common Ancestor of a Binary Tree Medium
236. Lowest Common Ancestor of a Binary Tree Medium https://leetcode.com/problems/lowest-common-ance ...
- 88 Lowest Common Ancestor of a Binary Tree
原题网址:https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description 描述 给定一棵二叉树 ...
- 【刷题-LeetCode】236. Lowest Common Ancestor of a Binary Tree
Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) o ...
随机推荐
- 开源MVCPager
PagedList<EntityName> list = filterList.OrderBy(m => m.Exp1).Reverse().ToPagedList2(id, );/ ...
- pycharm运行脚本为何不生成测试报告?
今日使用python+selenium编写自动化测试脚本并执行过程中,使用pycharm运行结果后发现脚本运行无报错,脚本中的操作也正常被执行,但就是没有生成测试报告. 为什么呢,为什么呢,生成测试报 ...
- hibernate(六) cascade(级联)和inverse关系详解
序言 写这篇文章之前,自己也查了很多的资料来搞清楚这两者的关系和各自所做的事情,但是百度一搜,大多数博文感觉说的云里雾里,可能博主自己清楚是怎么一回事,但是给一个不懂的人或者一知半解的人看的话,别人也 ...
- PC端和移动端地址适配
判断当前页面的打开方式是pc还是移动设备,如果是移动设备,跳转到对应移到端网站的方法: 方法一.还是用@media screen 思路:css使用媒体查询,当屏幕小于760px时,使某个元素的样式发生 ...
- css text-align-last设置末尾文本对齐方式
text-align-last:auto | start | end | left | right | center | justify auto: 无特殊对齐方式. left: 内容左对齐. cen ...
- Tcl Tk Introduction
Tcl Tk Introduction eryar@163.com 摘要Abstract:Tcl/Tck脚本可以很容易实现用户自定义的命令,方便的创建图形化的用户界面GUI,所以Tcl和Tk的应用领域 ...
- .NET面试题解析(03)-string与字符串操作
系列文章目录地址: .NET面试题解析(00)-开篇来谈谈面试 & 系列文章索引 字符串可以说是C#开发中最常用的类型了,也是对系统性能影响很关键的类型,熟练掌握字符串的操作非常重要. 常 ...
- SQL*Loader之CASE2
CASE2 1. 控制文件 [oracle@node3 ulcase]$ cat ulcase2.ctl -- NAME -- ulcase2.ctl - SQL*Loader Case Study ...
- javaWeb之maven多数据库环境的配置信息
在使用maven构建的web项目里,不管采用的是什么orm框架,数据库写死了必然不是最灵活的方式.所以通过maven 的buid方式可以动态的分配数据库信息 比如在jdbc.properties中,可 ...
- 用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片
用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片 ticons的用法可以百度 这里记录下具体的编译方法 在安装了ticons和ImageMagickDisp ...