如何在递归表中获得最低的2行公共父级(SQL)

时间:2009-03-03 20:39:14

标签: sql sql-server-2005 tsql recursion

假设我们有一个经典的'经理ID'递归关系表:

用户   user_id int   manager_id int(指user_id)

如果您在表中随机选择2行 - 或2个节点 - 您如何找到最低级别的共同祖先?我的平台是SQL Server 2005(Transact-SQL),但任何符合ANSI标准的SQL也可以工作......

2 个答案:

答案 0 :(得分:3)

对Quassnoi的回答进行了一些小编辑,它的确有效:

WITH
    hier1 (id, parent) AS (
    SELECT      id, parent
    FROM        table
    WHERE       id = @user1
    UNION ALL
    SELECT      id, parent
    FROM        table l, hier1 h
    WHERE       l.id = h.parent
    ),
    hier2 (id, parent) AS (
    SELECT      id, parent
    FROM        table
    WHERE       id = @user2
    UNION ALL
    SELECT      id, parent
    FROM        table l, hier1 h
    WHERE       l.id = h.parent
    )
SELECT  TOP 1 hier1.id
FROM    hier1, hier2
WHERE   hier1.id = hier2.id

答案 1 :(得分:2)

WITH
    hier1 (id, parent) AS (
    SELECT  id, parent
    FROM    table l
    WHERE   id = @user1
    UNION ALL
    SELECT  id, parent
    FROM    table l, hier1 h
    WHERE   l.id = parent
    ),
    hier2 (id, parent) AS (
    SELECT  id, parent
    FROM    table l
    WHERE   id = @user2
    UNION ALL
    SELECT  id, parent
    FROM    table l, hier1 h
    WHERE   l.id = parent
    ),
SELECT  TOP 1 hier1.id
FROM    hier1, hier2
WHERE   hier1.id = hier2.id