首页 > 解决方案 > CTE - 获取父级

问题描述

我知道有很多关于 CTE 的问题,但我仍然不知道该怎么做。我有包含列的表消息: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

标签: sqlsql-server

解决方案


您可以尝试如下。

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


推荐阅读