查找单表链中的最后一条记录 (SQL Server)

查找单表链中的最后一条记录 (SQL Server)

问题描述:

SQL Server 2005中得到这个表,用来维护合并操作的历史记录:

Got this table in SQL Server 2005, which is used to maintain a history of merging operations:

  • 列 FROM_ID (int)
  • TO_ID 列(整数)

现在我需要一个将原始 FROM_ID 作为输入并返回最后一个可用 TO_ID 的查询.

Now I need a query that takes the original FROM_ID as input, and returns the last available TO_ID.

例如:

  • ID 1 合并到 ID 2
  • 稍后,ID 2 合并到 ID 3
  • 再一次,ID 3 合并到 ID 4

因此,我尝试组合的查询将作为输入(在我假设的 WHERE 子句中)ID 1,并且应该给我最后一个可用的 TO_ID 作为结果,在本例中为 4.

So the query I'm trying to put together will take as input (in the WHERE clause I presume) ID 1, and should give me the last available TO_ID as a result, in this case 4.

我想我需要一些递归逻辑,但不知道如何开始.

I suppose I need some recursion logic, but don't really know how to start.

谢谢!

马修

使用 CTE 会起作用.

测试脚本

DECLARE @IDs TABLE (
  FromID INTEGER
  , ToID INTEGER
)

INSERT INTO @IDs
SELECT           1, 2 
UNION ALL SELECT 2, 3
UNION ALL SELECT 3, 4

SQL 语句

;WITH q AS (
    SELECT  FromID, ToID
    FROM    @IDs
    UNION ALL 
    SELECT  q.FromID, u.ToID
    FROM    q
            INNER JOIN @IDs u ON u.FromID = q.ToID
)
SELECT  FromID, MAX(ToID)
FROM    q
WHERE   FromID = 1
GROUP BY
        FromID