PostgreSQL遞迴查詢實現樹狀結構查詢

來源:互聯網
上載者:User

標籤:postgresql   遞迴   

在Postgresql的使用過程中發現了一個很有意思的功能,就是對於需要類似於樹狀結構的結果可以使用遞迴查詢實現。比如說我們常用的公司部門這種資料結構,一般我們設計表結構的時候都是類似下面的SQL,其中parent_id為NULL時表示頂級節點,否則表示上級節點ID。

CREATE TABLE DEPARTMENT ( ID INTEGER PRIMARY KEY, NAME VARCHAR(32), PARENT_ID INTEGER REFERENCES DEPARTMENT(ID));

下面我們造幾條測試資料

INSERT INTO DEPARTMENT(ID, NAME, PARENT_ID) VALUES(1, ‘DEPARTMENT_1‘, NULL);INSERT INTO DEPARTMENT(ID, NAME, PARENT_ID) VALUES(11, ‘DEPARTMENT_11‘, 1);INSERT INTO DEPARTMENT(ID, NAME, PARENT_ID) VALUES(12, ‘DEPARTMENT_12‘, 1);INSERT INTO DEPARTMENT(ID, NAME, PARENT_ID) VALUES(111, ‘DEPARTMENT_111‘, 11);INSERT INTO DEPARTMENT(ID, NAME, PARENT_ID) VALUES(121, ‘DEPARTMENT_121‘, 12);INSERT INTO DEPARTMENT(ID, NAME, PARENT_ID) VALUES(122, ‘DEPARTMENT_122‘, 12);

其中
- DEPARTMENT_1是頂級節點,它有兩個子節點?DEPARTMENT_11和?DEPARTMENT_12。
- DEPARTMENT_11節點又有一個子節點?DEPARTMENT_111。
?- DEPARTMENT_12節點有兩個子節點?DEPARTMENT_121和?DEPARTMENT_122。?

下面是遞迴查詢產生樹狀結構查詢語句

WITH RECURSIVE T (ID, NAME, PARENT_ID, PATH, DEPTH)  AS (    SELECT ID, NAME, PARENT_ID, ARRAY[ID] AS PATH, 1 AS DEPTH    FROM DEPARTMENT    WHERE PARENT_ID IS NULL    UNION ALL    SELECT  D.ID, D.NAME, D.PARENT_ID, T.PATH || D.ID, T.DEPTH + 1 AS DEPTH    FROM DEPARTMENT D    JOIN T ON D.PARENT_ID = T.ID    )    SELECT ID, NAME, PARENT_ID, PATH, DEPTH FROM TORDER BY PATH;
ID  NAME            PARENT_ID   PATH      DEPTH1   DEPARTMENT_1                1         111  DEPARTMENT_11   1           1,11      2111 DEPARTMENT_111  11          1,11,111  312  DEPARTMENT_12   1           1,12      2121 DEPARTMENT_121  12          1,12,121  3122 DEPARTMENT_122  12          1,12,122  3

轉載請以連結形式標明本文地址
本文地址:http://blog.csdn.net/kongxx/article/details/47035491

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

PostgreSQL遞迴查詢實現樹狀結構查詢

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.