我应该在CTE内部还是外部过滤分层查询的结果

时间:2015-08-10 11:37:23

标签: sql-server-2008 common-table-expression sql-execution-plan

我有两个选项可以过滤分层查询的结果 - 在CTE或主查询中。请参阅Original Question for reference

例如,这是第一个选项:

WITH CurrentRequests AS (
  SELECT
    id,
    RequestID,
    OldRequestID ,
    RequestID as TopRequestID
  FROM
    Requests
  WHERE RequestID = 6
  UNION ALL SELECT
    R.id,
    R.RequestID,
    R.OldRequestID, 
    C.TopRequestID as TopRequestID
  FROM
    CurrentRequests C
    INNER JOIN Requests R
      ON R.RequestID = C.OldRequestID
)
SELECT *
FROM
 CurrentRequests; 

SqlFiddle A

与第二名相比:

WITH CurrentRequests AS (
  SELECT
    id,
    RequestID,
    OldRequestID ,
    RequestID as TopRequestID
  FROM
    Requests
  UNION ALL SELECT
    R.id,
    R.RequestID,
    R.OldRequestID, 
    C.TopRequestID as TopRequestID
  FROM
    CurrentRequests C
    INNER JOIN Requests R
      ON R.RequestID = C.OldRequestID
)
SELECT *
FROM
 CurrentRequests 
WHERE TopRequestID  = 6; 

SqlFiddle B

执行计划看起来一样。

我应该优先考虑一个选项,还是一样?

0 个答案:

没有答案