我有两个选项可以过滤分层查询的结果 - 在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;
与第二名相比:
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;
执行计划看起来一样。
我应该优先考虑一个选项,还是一样?