2016-11-29 63 views
1

我對這裏使用CTE內部連接感到困惑。內部連接中出現了什麼,以及cte1 c中的內容?令人困惑的使用cte,inner join和union全部

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

要了解,您可以運行每個部分獨立,然後建立完整的查詢。 – jarlh

+4

這是一個遞歸CTE。請參閱https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx – HoneyBadger

+0

內部聯接之前,cte1中的內容是什麼? –

回答

1

這是一個遞歸CTEhidden-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 [email protected] This is - probably - one single element 

--The接下來選擇將「添加」到結果集

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 

結果應該是給定元素的父母的完整遞歸列表。

+0

非常感謝 –