我有一张桌子(users_groups
):
+-----------+------------+---------+
| groupGUID | memberGUID | isGroup |
+-----------+------------+---------+
| 32AB160C | 5B277276 | 0 |
| 32AB160C | 0A023D1D | 0 |
| 5C952B2E | 32AB160C | 1 |
| 4444FTG5 | 5C952B2E | 1 |
+-----------+------------+---------+
isGroup
列指示memberGUID
是否为组。
我想获取一个新的表(new_users_groups
),其中所有组成员身份都已解决:
+-----------+------------+
| groupGUID | memberGUID |
+-----------+------------+
| 32AB160C | 5B277276 |
| 32AB160C | 0A023D1D |
| 5C952B2E | 5B277276 |
| 5C952B2E | 0A023D1D |
| 4444FTG5 | 5B277276 |
| 4444FTG5 | 0A023D1D |
+-----------+------------+
目前,我正在手动进行所有操作:
正在寻找所有组的memberGUID
SELECT * FROM users_groups WHERE isGroup = 1;
对于上一步返回的所有组,找到其成员
SELECT * FROM users_groups WHERE groupGUID = '5C952B2E'
如果成员不是组,则将其插入新表中
INSERT INTO new_users_groups (groupGUID, memberGUID) VALUES ('5C952B2E', '5B277276');
INSERT INTO new_users_groups (groupGUID, memberGUID) VALUES ('5C952B2E', '0A023D1D');
如果成员是组,请转到步骤2。
我该如何自动化?也许使用递归CTE?
答案 0 :(得分:4)
您可以使用递归CTE来做到这一点:
with cte as (
select ug.groupGUID, ug.groupGUID as grp, ug.memberGUID
from user_groups ug
where isGroup = 0
union all
select ug.groupGUID, ug.groupGUID as grp, cte.memberGUID
from user_groups ug join
cte
on cte.grp = ug.memberGUID
)
select groupGUID, memberGUID
from cte;
这里是Rextester。
答案 1 :(得分:0)
尝试CROSS JOIN
SELECT t1.groupGUID, t2.memberGUID
FROM temp t1, temp t2 WHERE t2.isGroup = 0
GROUP BY t1.groupGUID, t2.memberGUID