Here's the jist of the problem: Given a list of sets, such as:
[ (1,2,3), (5,2,6), (7,8,9), (6,12,13), (21,8,34), (19,20) ]
Return a list of groups of the sets, such that sets that have a shared element are in the same group.
[ [ (1,2,3), (5,2,6), (6,12,13) ], [ (7,8,9), (21,8,34) ], [ (19,20) ] ]
Note the stickeyness - the set (6,12,13) doesn't have a shared element with (1,2,3), but they get put in the same group because of (5,2,6).
To complicate matters, I should mention that I don't really have these neat sets, but rather a DB table with several million rows that looks like:
element | set_id
----------------
1 | 1
2 | 1
3 | 1
5 | 2
2 | 2
6 | 2
and so on. So I would love a way to do it in SQL, but I would be happy with a general direction for the solution.
EDIT: Changed the table column names to (element, set_id) instead of (key, group_id), to make the terms more consistent. Note that Kev's answer uses the old column names.