I have one table (users_groups
) :
+-----------+------------+---------+
| groupGUID | memberGUID | isGroup |
+-----------+------------+---------+
| 32AB160C | 5B277276 | 0 |
| 32AB160C | 0A023D1D | 0 |
| 5C952B2E | 32AB160C | 1 |
| 4444FTG5 | 5C952B2E | 1 |
+-----------+------------+---------+
isGroup
column indicates whether memberGUID
is a group or not.
I want to obtain a new table (new_users_groups
) with all group memberships resolved :
+-----------+------------+
| groupGUID | memberGUID |
+-----------+------------+
| 32AB160C | 5B277276 |
| 32AB160C | 0A023D1D |
| 5C952B2E | 5B277276 |
| 5C952B2E | 0A023D1D |
| 4444FTG5 | 5B277276 |
| 4444FTG5 | 0A023D1D |
+-----------+------------+
For now, I'm doing everything manually :
Looking for all group's memberGUID
SELECT * FROM users_groups WHERE isGroup = 1;
For all groups returned by previous step, find its members
SELECT * FROM users_groups WHERE groupGUID = '5C952B2E'
If members are not groups, insert them into a new table
INSERT INTO new_users_groups (groupGUID, memberGUID) VALUES ('5C952B2E', '5B277276'); INSERT INTO new_users_groups (groupGUID, memberGUID) VALUES ('5C952B2E', '0A023D1D');
If members are groups, go to step 2.
How can I automate this? Maybe with a Recursive CTE ?