SQL query to get full hierarchy path from different tables

依然范特西╮ 提交于 2019-12-10 10:38:38

问题


This is very relevant to the question SQL query to get full hierarchy path.

The only difference is that my hierarchy contains different entity types from different tables, for example:

  1. Project
  2. Phase
  3. Folder
  4. Document

I want to select all documents along with their full paths (from poject level to folder level). Phases and folders can have subphases and folders.

I'm horrible at SQL and just can't figure out how to adapt the answer to the linked question to suit my needs.

Data model and example data

DECLARE @Project TABLE (ID INTEGER, Name VARCHAR(32))
DECLARE @Phase TABLE (ID INTEGER, Project_ID INTEGER, Parent_Phase_ID INTEGER, Name VARCHAR(32))
DECLARE @Folder TABLE (ID INTEGER, Phase_ID INTEGER, Parent_Folder_ID INTEGER, Name VARCHAR(32))
DECLARE @Document TABLE (ID INTEGER, Folder_ID INTEGER, Name VARCHAR(32))

INSERT INTO @Project VALUES (1, 'MyProject')

INSERT INTO @Phase
  SELECT 1, 1, 0, 'MyPhase1'
  UNION ALL SELECT 2, 1, 1, 'MyPhase1_1'
  UNION ALL SELECT 3, 1, 0, 'MyPhase2'

INSERT INTO @Folder
  SELECT 1, 1, 0, 'MyFolder'
  UNION ALL SELECT 2, 1, 1, 'MySubFolder'
  UNION ALL SELECT 3, 1, 0, 'AnotherFolder'

INSERT INTO @Document
  SELECT 1, 2, 'MyDocument'
  UNION ALL SELECT 2, 3, 'AnotherDocument'

Example

MyProject1 ................ Project
- MyPhase1 ................ Phase
  - MyPhase1_1 ............ Phase
    - MyFolder ............ Folder
      - MySubfolder ....... Folder
        - MyDocument ...... Document
    - AnotherFolder ....... Folder
      - AnotherDocument ... Document
- MyPhase2 ................ Phase

Ideal query results in this case:

Document        | Path
MyDocument      | MyProject1/MyPhase1/MyPhase1_1/MyFolder/MySubfolder  
AnotherDocument | MyProject1/MyPhase1/MyPhase1_1/AnotherFolder

回答1:


From what you have shown, I would assume you have 4 tables with a one to many relation between Project and Phase, Phase and Folder and Folder and Document.

Your SQL Statement then could be as simple as joining them all together

SELECT *
FROM   Projects p
       INNER JOIN Phases ph ON ph.ProjectID = p.ProjectID
       INNER JOIN Folders f ON f.PhaseID = ph.PhaseID
       INNER JOIN Documents d ON d.FolderID = f.FolderID

I really don't see a need yet to make it more difficult than need be by throwing in CTE's



来源:https://stackoverflow.com/questions/5549480/sql-query-to-get-full-hierarchy-path-from-different-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!