etrex
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # postgresql 樹狀結構 ## 什麼是樹狀結構 ![](https://i.imgur.com/zwwp1Tf.png) ![](https://i.imgur.com/jTS00JK.png) ## 可能的使用情境 - 目錄/麵包屑/分類/子分類 - 物料清單 - 討論串 ## 範例樹 ![](https://i.imgur.com/HDcHDvX.png) ## 可能的解決方案 ### Adjacency list 使用一個 parent_id 來儲存關聯,假設是討論串的情境,則欄位如下: - id - parent_id - content 資料如下: | id | parent_id | content | |--- |-----------|---------| | 1 | NULL | aa | | 2 | 1 | bb | | 3 | 1 | cc | | 4 | 2 | dd | | 5 | 3 | ee | | 6 | 4 | ff | | 7 | 4 | gg | #### 查詢父層 ```sql SELECT parent.* from adjancency_lists node join adjancency_lists parent on node.parent_id = parent.id where node.id = 4; ``` #### 查詢子層 ```sql SELECT * from adjancency_lists node where parent_id = 4; ``` #### 查詢所有祖先 WITH RECURSIVE CTE 參考文件:https://www.postgresql.org/docs/current/queries-with.html ```sql WITH RECURSIVE ancestors(id, parent_id, content) AS ( SELECT node.id, node.parent_id, node.content FROM adjancency_lists node WHERE id = 4 UNION ALL SELECT node.id, node.parent_id, node.content FROM adjancency_lists node JOIN ancestors ON ancestors.parent_id = node.id ) SELECT * FROM ancestors; ``` #### 查詢所有後代 ```sql WITH RECURSIVE decendants(id, parent_id, content) AS ( SELECT node.id, node.parent_id, node.content FROM adjancency_lists node WHERE id = 4 UNION ALL SELECT node.id, node.parent_id, node.content FROM adjancency_lists node JOIN decendants ON decendants.id = node.parent_id ) SELECT * FROM decendants; ``` #### 寫入節點 ```sql INSERT INTO adjancency_lists(parent_id, content) VALUES (4, 'qq'); SELECT * from adjancency_lists; INSERT INTO adjancency_lists(parent_id, content) VALUES (10, 'qqq'); ``` #### 刪除節點(包含後代)使用 foreign_key 連動刪除 ```sql delete from adjancency_lists where id = 10; ``` ### Path enumeration / Materialized Path 使用一個 path 字串([或陣列](https://medium.com/notes-from-a-messy-desk/representing-trees-in-postgresql-cbcdae419022))欄位來儲存關聯,假設是討論串的情境,則欄位如下: - id - path - content 資料如下: | id | path | content | |----|----------|---------| | 1 | | aa | | 2 | 1/ | bb | | 3 | 1/ | cc | | 4 | 1/2/ | dd | | 5 | 1/3/ | ee | | 6 | 1/2/4/ | ff | | 7 | 1/2/4/ | gg | 其中,path 可以是天然的麵包屑 #### 查詢 id 4 的父層 ```sql SELECT * from materialized_paths where path = '1/2/' ; ``` #### 查詢 id 4 的子層 ```sql SELECT * from materialized_paths where path = '1/2/4/'; ``` #### 查詢 id 4 的所有祖先 ```sql SELECT * from materialized_paths where '1/2/' ~* path; ``` #### 查詢 id 4 的所有後代 ```sql SELECT * from materialized_paths where path ~* '1/2/'; ``` #### 寫入節點 ```sql INSERT INTO materialized_paths(path, content) VALUES ('1/2/4/', 'gg'); SELECT * from materialized_paths; INSERT INTO materialized_paths(path, content) VALUES ('1/2/4/11/', 'qqq'); ``` #### 刪除節點(包含後代) ```sql delete from materialized_paths where id = 11 or path ~* '1/2/4/11'; ``` ### Nested sets ![](https://i.imgur.com/3ZQKEvy.png) ![](https://i.imgur.com/Q2IMp8I.png) ![](https://i.imgur.com/ppovKXk.png) 使用兩個數字欄位(left, right)來儲存關聯,假設是討論串的情境,則欄位如下: - id - left - right - content 資料如下: | id | left | right | content | |----|------|-------|---------| | 1 | 1 | 14 | aa | | 2 | 2 | 9 | bb | | 3 | 10 | 13 | cc | | 4 | 3 | 8 | dd | | 5 | 11 | 12 | ee | | 6 | 4 | 5 | ff | | 7 | 6 | 7 | gg | #### 查詢 id 4 的父層 ```sql SELECT parent.* from nested_sets node join nested_sets parent on node.left BETWEEN parent."left" + 1 and parent."right" - 1 where node.id = 4 order by parent.right limit 1; ``` #### 查詢 id 4 的子層 [因為太麻煩了所以可能多儲存一個 depth](https://en.wikipedia.org/wiki/Nested_set_model#Variations) ```sql SELECT node.* from nested_sets node join nested_sets parent on node.left BETWEEN parent."left" + 1 and parent."right" - 1 where parent.id = 4 and not exists ( select * from nested_sets mid where mid.left BETWEEN parent.left + 1 and parent.right - 1 and node.left BETWEEN mid.left + 1 and mid.right - 1 ); ``` #### 查詢 id 4 的所有祖先 ```sql SELECT parent.* from nested_sets node join nested_sets parent on node.left BETWEEN parent."left" and parent."right" where node.id = 4; ``` #### 查詢 id 4 的所有後代 ```sql SELECT node.* from nested_sets node join nested_sets parent on node.left BETWEEN parent."left" and parent."right" where parent.id = 4; ``` #### 寫入節點 ```sql select "right" from nested_sets where id = 4; update nested_sets set "right" = "right" + 2 WHERE "right" >= 8; update nested_sets set "left" = "left" + 2 WHERE "left" >= 8; insert into nested_sets("left", "right", content) values (8,9,'qq'); -- 看一下寫入的狀況 select * from nested_sets order by "left", "right" desc; -- 再寫入一筆 select "right" from nested_sets where id = 8; update nested_sets set "right" = "right" + 2 WHERE "right" >= 9; update nested_sets set "left" = "left" + 2 WHERE "left" >= 9; insert into nested_sets("left", "right", content) values (9,10,'qqq'); select * from nested_sets order by "left", "right" desc; ``` #### 刪除節點(包含後代) ```sql select "left", "right" from nested_sets where id = 8; delete from nested_sets where "left" >= 8 and "right" <= 11; update nested_sets set "left" = "left" - (11-8+1) WHERE "left" >= 11; update nested_sets set "right" = "right" - (11-8+1) WHERE "right" >= 11; ``` ### Subsets / Closure table 使用一個資料表來儲存關聯,假設是討論串的情境,則欄位如下: - closeure_table_comments - id - content - closeure_table_relations - ancestor_id - descendant_id - length 資料如下: - closeure_table_comments | id | content | |----|---------| | 1 | aa | | 2 | bb | | 3 | cc | | 4 | dd | | 5 | ee | | 6 | ff | | 7 | gg | - closeure_table_relations | id | ancestor_id | dencendant_id | length | |----|-------------|---------------|--------| | 2 | 1 | 1 | 0 | | 3 | 1 | 2 | 1 | | 4 | 1 | 3 | 1 | | 5 | 1 | 4 | 2 | | 6 | 1 | 5 | 2 | | 7 | 1 | 6 | 3 | | 8 | 1 | 7 | 3 | | 9 | 2 | 2 | 0 | | 10 | 2 | 4 | 1 | | 11 | 2 | 6 | 2 | | 12 | 2 | 7 | 2 | | 13 | 3 | 3 | 0 | | 14 | 3 | 5 | 1 | | 15 | 4 | 4 | 0 | | 16 | 4 | 6 | 1 | | 17 | 4 | 7 | 1 | | 18 | 5 | 5 | 0 | | 19 | 6 | 6 | 0 | | 20 | 7 | 7 | 0 | #### 查詢 id 4 的父層 ```sql select c.* from closeure_table_comments c join closeure_table_relations r on ancestor_id = c.id where r.dencendant_id = 4 and r."length" = 1; ``` #### 查詢 id 4 的子層 ```sql select c.* from closeure_table_comments c join closeure_table_relations r on dencendant_id = c.id where r.ancestor_id = 4 and r."length" = 1; ``` #### 查詢 id 4 的所有祖先 ```sql select c.* from closeure_table_comments c join closeure_table_relations r on ancestor_id = c.id where r.dencendant_id = 4 and r."length" >= 1; ``` #### 查詢 id 4 的所有後代 ```sql select c.* from closeure_table_comments c join closeure_table_relations r on dencendant_id = c.id where r.ancestor_id = 4 and r."length" >= 1; ``` #### 寫入節點 ```sql insert into closeure_table_comments("content") values('QQ'); select * from closeure_table_comments; insert into closeure_table_relations(ancestor_id, dencendant_id, "length") SELECT ancestor_id, 8 as dencendant_id, length + 1 as length FROM closeure_table_relations WHERE dencendant_id = 4 union select 8,8,0; -- 看一下寫入的狀況 select * from closeure_table_relations; -- 再寫入一筆 insert into closeure_table_comments("content") values('QQQ'); select * from closeure_table_comments; insert into closeure_table_relations(ancestor_id, dencendant_id, "length") SELECT ancestor_id, 9 as dencendant_id, length + 1 as length FROM closeure_table_relations WHERE dencendant_id = 8 union select 9,9,0; ``` #### 刪除節點(包含後代) ```sql select dencendant_id from closeure_table_relations where ancestor_id = 8; delete from closeure_table_relations where dencendant_id in (8,9); delete from closeure_table_comments where id in (8,9); ``` ## 結論 - RECURSIVE CTE 好像還不錯 - 大量寫入、少量查詢時,使用 Adjancency list - 資料量大但是不高(depth)的樹,使用 Closure Table 或 Materialized Path - Nested Set 感覺比較遜,但是我都沒實測過 - 需要在真實的大量資料上實測各種方法實際的效能(搭配 index) ## 相關套件 - ltree: https://www.postgresql.org/docs/current/ltree.html - hierarchy-data-closure-table: https://github.com/developerworks/hierarchy-data-closure-table ## 參考資料 - https://www.facebook.com/etrex.kuo/posts/2725099867500858 - https://blog.frost.tw/posts/2017/10/23/Use-PostgreSQL-s-recursive-query-to-find-ancestors/ - https://www.slideshare.net/billkarwin/models-for-hierarchical-data - https://www.postgresql.org/docs/current/queries-with.html - https://bitworks.software/en/2017-10-20-storing-trees-in-rdbms.html

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully