如何在父子链中对祖先进行分组

时间:2013-08-18 13:10:38

标签: sql group-by parent-child

我在表格中有两列,例如:

ID1,ID2
1,2
3,4
4,5
7,8
8,10
9,10
9,11
11,12
..,..

所以,我想将这些ID关联在同一个组中:

ID Group_ID
1,1
2,1
3,2
4,2
5,2
7,3
8,3
9,3
10,3
11,3
12,3
..,..

PS:在这些例子中,3等于4,4等于5,因此4应该等于5.而且,7,8,9,10,11,12应该是相同的组id。我试图这样做,如果A = B而B = C则A应该等于C(A = C)。

1 个答案:

答案 0 :(得分:0)

不漂亮,但这可以使用常规SQL:

SELECT * FROM
(SELECT ID1 AS ID, Group_ID
 FROM
 (SELECT t1.ID1 AS ID1,
         t1.ID2 AS ID2,
         t2.ID1 AS ID3,
         t2.ID2 AS ID4,
         (SELECT COUNT(*) + 1
          FROM ids t3
          LEFT JOIN ids t4
          ON t3.ID2 = t4.ID1
          OR (t3.ID1 = t4.ID1 AND t3.ID2 <> t4.ID2)
          OR (t3.ID2 = t4.ID2 AND t3.ID1 <> t4.ID1)
          WHERE (t3.ID1 < t1.ID1 
                 OR (t3.ID1 = t1.ID1 AND t3.ID2 < t1.ID2))
          AND t4.ID1 IS NULL) AS Group_ID
  FROM ids t1
  LEFT JOIN ids t2
  ON t1.ID2 = t2.ID1
  OR (t1.ID1 = t2.ID1 AND t1.ID2 <> t2.ID2)
  OR (t1.ID2 = t2.ID2 AND t1.ID1 <> t2.ID1)) sub1
 UNION DISTINCT
 SELECT ID2 AS ID, Group_ID
 FROM
 (SELECT t1.ID1 AS ID1,
         t1.ID2 AS ID2,
         t2.ID1 AS ID3,
         t2.ID2 AS ID4,
         (SELECT COUNT(*) + 1
          FROM ids t3
          LEFT JOIN ids t4
          ON t3.ID2 = t4.ID1
          OR (t3.ID1 = t4.ID1 AND t3.ID2 <> t4.ID2)
          OR (t3.ID2 = t4.ID2 AND t3.ID1 <> t4.ID1)
          WHERE (t3.ID1 < t1.ID1 
                 OR (t3.ID1 = t1.ID1 AND t3.ID2 < t1.ID2))
          AND t4.ID1 IS NULL) AS Group_ID
  FROM ids t1
  LEFT JOIN ids t2
  ON t1.ID2 = t2.ID1
  OR (t1.ID1 = t2.ID1 AND t1.ID2 <> t2.ID2)
  OR (t1.ID2 = t2.ID2 AND t1.ID1 <> t2.ID1)) sub2
) sub3
ORDER BY ID

请参阅SQL Fiddle Demo