开发者社区> 问答> 正文

无法理解WITH…TempTable如何获取额外的行

我有一个叫Property2列的表PropertyRSN,ParentPropertyRSN

数据

propertyRSN | parentpropertyRSN
19          | 3
18          | 6
27          | 7
12          | 9
13          | 9
16          | 12

WITH tempTable(PLRSN, PRSN) AS (
   SELECT PropertyRSN, Property.ParentPropertyRSN 
   FROM Property 
   WHERE PropertyRSN = 16
   UNION ALL
   SELECT nplus1.PropertyRSN, nplus1.ParentPropertyRSN 
   FROM Property as nplus1, tempTable 
   WHERE tempTable.prsn = nplus1.PropertyRSN
)
SELECT PLRSN, PRSN 
FROM tempTable

结果

PLRSN | PRSN
16    | 12
12    | 9
9     | NULL

问题-我无法理解temTable查询如何获取包含数据的行9 | NULL?我也无法理解如何在方括号内使用TemTable?

================================================== ===================

create table property (propertyRSN int, ParentPropertyRSN int);
Insert into property (propertyRSN, ParentPropertyRSN) values (19,3);
Insert into property (propertyRSN, ParentPropertyRSN) values (18,6);
Insert into property (propertyRSN, ParentPropertyRSN) values (27,7);
Insert into property (propertyRSN, ParentPropertyRSN) values (12,9);
Insert into property (propertyRSN, ParentPropertyRSN) values (13,9);
Insert into property (propertyRSN, ParentPropertyRSN) values (16,12);

展开
收起
祖安文状元 2020-01-03 16:20:48 487 0
1 条回答
写回答
取消 提交回答
  • 您的CTE恰好是递归 CTE,我会选择使用显式联接来编写它:

    WITH tempTable (PLRSN, PRSN) AS (
        SELECT PropertyRSN, Property.ParentPropertyRSN
        FROM Property
        WHERE PropertyRSN = 16
    
        UNION ALL
    
        SELECT nplus1.PropertyRSN, nplus1.ParentPropertyRSN
        FROM Property AS nplus1
        INNER JOIN tempTable t ON t.prsn = nplus1.PropertyRSN
    )
    
    SELECT PLRSN, PRSN FROM tempTable;
    
    2020-01-03 16:21:00
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载