Using Recursive Common table expressions to represent Tree structures

来源:http://www.cnblogs.com/kungfupanda/archive/2016/06/29/5625709.html
-Advertisement-
Play Games

http://www.postgresonline.com/journal/archives/131-Using-Recursive-Common-table-expressions-to-represent-Tree-structures.html Tree Problem and was bas ...


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.

The Problem

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_idsi_parentidsi_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
Posted by Leo Hsu and Regina Obe in 8.4, basics, cte, intermediate at 13:44 | Comments (8) | Trackback (1) Defined tags for this entry: Related entries by tags:
Trackbacks Trackback specific URI for this entry
Social comments and analytics for this post
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 Weblog: uberVU - social comments
Tracked: Jan 04, 21:19 PingBack
Weblog: www.postgresonline.com
Tracked: Aug 20, 00:58

 


Comments Display comments as (Linear | Threaded)
Great topic!

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; #1 David Fetter (Homepage) on 2009-08-16 19:10 Have thought about using ltree ?

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 ;-) #2 Arek on 2009-09-19 18:16 Good point. We haven't explored the use of ltree so 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) #2.1 Leo on 2009-09-28 02:58 How do you use it to find the parent path for just a single item? #3 sabra on 2009-09-26 18:35 Sabra,

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. #3.1 Leo on 2009-09-28 03:05 many thanks for this great example.i implemented the child to parent recursion in case someone needs it:

--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; #4 krishnen on 2010-02-16 15:24 Great example for recursive CTE. Very useful. Thanks! #5 Shirish on 2010-09-30 11:05 this is most easy

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 #6 vakan (Homepage) on 2011-01-13 16:14
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一. 表空間相關命令 創建數據表空間 create SMALLFILE tablespace dataSpace datafile 'E:\oracle\product\10.2.0\oradata\orcl\dataSpace.dbf' SIZE 50M autoextend on next 10 ...
  • WITH RECURSIVE and MySQL If you have been using certain DBMSs, or reading recent versions of the SQL standard, you are probably aware of the so-called ...
  • 官方文檔:http://hbase.apache.org/book.html java簡單操作hbase的表 ...
  • 一、概述: 字元串類型是Redis中最為基礎的數據存儲類型,它在Redis中是二進位安全的,這便意味著該類型可以接受任何格式的數據,如JPEG圖像數據或Json對象描述信息等。在Redis中字元串類型的Value最多可以容納的數據長度是512M。二、相關命令列表: 三、命令示例: 1. SET/GE ...
  • 使用sql server的時候,免不了與xml的參數打交道,xml大多數時候都給我們的程式帶來方便,但是也有些時候會有變數賦值不通過的時候。(當然羅,如果你本身xml都通不過 xml spy 之類軟體的檢查的話那就不是這方面的範圍啦~) 今天分享的例子非常簡單,就測試幾個例子 例子1 : 我們平常見 ...
  • 介紹 作業也叫做事件調度,其實它也就是一個時間觸發器;它可以定義某個時間點執行指定的資料庫命令操作。 語法 CREATE [DEFINER = { user | CURRENT_USER }] ######定義創建人,預設創建事件的用戶就是事件的定義人,必須具備super許可權才能指定其他用戶。 EV ...
  • 一. 在sql server下處理需要導出的資料庫 1. 執行以下sql,查出所有'float'類型的欄位名,手動將float類型改為decimal(18,4). select 表名=d.name,欄位名=a.name,類型=b.name FROM syscolumns a left join sy ...
  • 本文為作者原創,轉載請註明原作者及轉載地址。 上一篇講瞭如何用thinkPHP框架實現數據的添加,那這一篇就講一下如何用thinkPHP實現數據的刪除和批量刪除吧。 預期效果圖: 原諒博主對照片的處理是如此的草率吧。。。 仍然是 通過MVC模式進行拆分: 首先是視圖部分: 仍然是採用表單傳值的方法, ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...