2009-03-03 7 views
3

Disons que nous avons, nous avons une table avec relation récursive les 'id manager' classique:Comment obtenir le plus bas, parent commun pour 2 lignes dans le tableau récursif (SQL)

utilisateurs user_id int manager_id int (se réfère à user_id)

Si vous sélectionnez aléatoirement 2 lignes dans le tableau ou 2 nœuds, comment trouvez-vous le niveau le plus bas, ancêtre commun? Ma plate-forme est SQL Server 2005 (Transact-SQL) mais toute SQL conforme à la norme ANSI travaillera également ...

Répondre

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 
3

Quelques modifications mineures à la réponse de Quassnoi, et cela fonctionne:

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 
+0

Quels ont été les modifications? Je ne vois aucune différence :) – Quassnoi

+0

h.parent , avant sélectionnez très mineur :) merci pour la réponse originale –

Questions connexes