这与问题SQL query to get full hierarchy path非常相关。
唯一的区别是我的层次结构包含来自不同表的不同实体类型,例如:
我想选择所有文档及其完整路径(从项目级别到文件夹级别)。阶段和文件夹可以包含子阶段和文件夹。
我对SQL很恐怖,只是无法弄清楚如何根据我的需要调整链接问题的答案。
数据模型和示例数据
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'
示例
MyProject1 ................ Project
- MyPhase1 ................ Phase
- MyPhase1_1 ............ Phase
- MyFolder ............ Folder
- MySubfolder ....... Folder
- MyDocument ...... Document
- AnotherFolder ....... Folder
- AnotherDocument ... Document
- MyPhase2 ................ Phase
在这种情况下理想的查询结果:
Document | Path
MyDocument | MyProject1/MyPhase1/MyPhase1_1/MyFolder/MySubfolder
AnotherDocument | MyProject1/MyPhase1/MyPhase1_1/AnotherFolder
答案 0 :(得分:1)
根据您的展示,我假设您有4个表格,Project and Phase
,Phase and Folder
和Folder and Document
之间存在一对多关系。
然后,您的SQL语句就像加入所有语句一样简单
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
我真的认为还没有必要通过投入CTE来让它变得更加困难