混淆使用cte,内部联接和联合所有

时间:2016-11-29 10:45:53

标签: sql sql-server common-table-expression

我对CTE上内连接的使用感到困惑。在内部联接中出现的内容是什么?cte1 c中的内容是什么?

WITH cte1 AS
      (SELECT id,geographyname,
              OriginalGoals,                
          ParentGeographyname,
          0 AS HierarchyLevel,
          paradigm
   FROM businessobject_RefinementMaster
   WHERE Id = @Geo
     UNION ALL
     SELECT a.id,
            a.geographyname,
            a.OriginalGoals,                
            a.ParentGeographyName,
            HierarchyLevel-1 AS HierarchyLevel,
            a.paradigm
     FROM businessobject_RefinementMaster a
     INNER JOIN cte1 c ON c.ParentGeographyname = a.geographyname
     AND c.paradigm=a.paradigm )

此查询的结果是什么?

1 个答案:

答案 0 :(得分:1)

这是递归CTE hidden-RBAR )。我会尝试以某种方式评论它,你可以理解,发生了什么:

WITH cte1 AS
(
    /*
    This is called "anchor" and reads the "head" lines of a hierarchy
    */
    SELECT id,
        geographyname,
        OriginalGoals,                
        ParentGeographyname,
        0 AS HierarchyLevel,             --obviously this starts with a "0"
        paradigm
    FROM businessobject_RefinementMaster --The source-table
    WHERE Id = @Geo                      --You read elements with Id=@Geo. This is - probably - one single element

- 下一个SELECT将“添加”到结果集

    UNION ALL

    /*
    The column-list must be absolutely the same (count and type) of the anchor
    */

    SELECT a.id,
        a.geographyname,
        a.OriginalGoals,                
        a.ParentGeographyName,
        HierarchyLevel-1 AS HierarchyLevel,                       --this is simple counting. Started with 0 this will lead to -1, -2, -3...
        a.paradigm
    FROM businessobject_RefinementMaster a                        --same source-table as above
    INNER JOIN cte1 c ON c.ParentGeographyname = a.geographyname  --Find rows where the name of the element is the parent-name of the former element
    AND c.paradigm=a.paradigm 
)

/*
Return the result-set
*/
SELECT * FROM cte1

结果应该是父元素到给定元素的完整递归列表。