我的表格包含两列RequestId
和OldRequestId
。
如果我传递RequestId
,它应该会检索我的具体记录。
如果检索到的记录中的OldRequestId
不为空,那么它也应该带来旧的请求数据。
它应该继续,直到OldRequestId
为空。
有人可以帮助我为此要求编写最好的SQL查询吗?
答案 0 :(得分:4)
您可以使用递归公用表表达式(CTE)解决此问题:
DECLARE
@RequestID int = 6;
WITH
ReqCTE AS
(
SELECT
RequestID,
OldRequestID
FROM
Requests
WHERE
RequestID = @RequestID
UNION ALL SELECT
R.RequestID,
R.OldRequestID
FROM
ReqCTE C
INNER JOIN Requests R
ON R.RequestID = C.OldRequestID
)
SELECT
*
FROM
ReqCTE;
答案 1 :(得分:1)
答案取决于您希望将旧请求链接到替换项的深度。如果它只是一个级别,您可以制作一个简单的LEFT JOIN
:
SELECT
n.RequestID,
COALESCE(r.RequestID, n.RequestID) AS CurrentRequestID,
n.OldRequestID
FROM
Requests n LEFT JOIN
Requests r ON n.RequestID = r.OldRequestID
WHERE 6 IN (r.RequestID, n.RequestID)
由于您希望将旧请求链接到最新请求,因此您需要使用CTE递归执行此操作:
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;