【问题标题】:SQL query to return a chain用于返回链的 SQL 查询
【发布时间】:2021-12-26 09:27:17
【问题描述】:

我有一个跟踪变化的表。一列称为beforename,另一列称为aftername

一些样本数据可能是:

Parent Child
a b
b c
c d

我正在尝试编写一个以返回更改的方式自我引用自身的查询,即:

a -> b -> c -> d (the arrows are just for notation here)

这可以在 SQL 中实现吗?

我的数据库是 SQL Server

【问题讨论】:

  • 是的。使用recursive cte
  • 我怀疑你需要一个合适的序列,比如日期时间或身份。

标签: sql sql-server tsql hierarchy chaining


【解决方案1】:

您可以使用递归公用表表达式 (CTE);

WITH cte(Root, Level, Parent, Child) AS (
  SELECT Parent, 0, Parent, Child FROM Table1 
     WHERE Parent NOT IN (SELECT Child FROM Table1)
  UNION ALL
  SELECT cte.Root, cte.Level + 1, t1.Parent, t1.Child 
  FROM cte 
  JOIN Table1 t1 
     ON cte.Child = t1.Parent AND cte.Level < 10
)
SELECT * FROM cte ORDER BY Root, Level;

基本上,递归 CTE 使用基本情况(查找所有起点)。这个用的;

SELECT Parent, 0, Parent, Child FROM Table1 
     WHERE Parent NOT IN (SELECT Child FROM Table1)

...查找所有父母,即在表中从未提及父母作为孩子的行。然后它将这些父级设置为“根”并将级别设置为 0。

然后它继续使用; 查找该根的子行;

SELECT cte.Root, cte.Level + 1, t1.Parent, t1.Child 
  FROM cte 
  JOIN Table1 t1 
     ON cte.Child = t1.Parent AND cte.Level < 10

...它基本上只是找到下一个子代​​(以该行为父代的行),同时保持根并增加 1 级。

它还将递归限制为 10 级,以防数据中存在循环。

A dbfiddle to test with

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多