我知道有很多关于 CTE 的问题,但我仍然不知道该怎么做。 我有表 Messages,其中包含以下列:id 和 previousMessageId。我怎样才能获得 id = 957 的父级 - 它应该是:950。
table Messages
--------------
id | previousMessageId
957 | 956
956 | 950
950 | NULL
这是我的查询:
WITH previous AS
(
SELECT id
FROM Messages
WHERE id = 957
UNION ALL
SELECT cur.id
FROM Messages cur
INNER JOIN previous ON cur.previousMessageID = previous.id
)
SELECT * FROM previous
它给了我:
957
958
但结果应该是:950
最佳答案
您可以尝试如下。
declare @table table(id int, previousMessageId int)
insert into @table select 957 , 956
insert into @table select 956 , 950
insert into @table select 950 , NULL
insert into @table select 999 , 998
insert into @table select 998 , 997
insert into @table select 997 , NULL
;WITH previous
AS (SELECT id,
previousmessageid
FROM @table
WHERE id = 957
UNION ALL
SELECT cur.id,
cur.previousmessageid
FROM @table cur
INNER JOIN previous
ON cur.id = previous.previousmessageid)
SELECT ID
FROM previous
WHERE previousmessageid IS NULL
在上面的示例中,对于 Id 957,您将获得 950,对于 Id 999,您将获得 997
关于sql - CTE-- 获取父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691340/