Files
bl/help/base_sys_user_role去重.sql
xinian ba1a1ffbea
All checks were successful
ci/woodpecker/push/my-first-workflow Pipeline was successful
refactor: 统一数据库约束维护位置
2026-04-27 00:57:18 +08:00

38 lines
946 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- base_sys_user_role 角色授权去重
-- 只处理未软删除的有效授权软删除历史记录不参与去重
-- 保留每组有效 userId + roleId id 最小的一条删除其余重复记录
-- 1. 执行前查看重复数据
SELECT
"userId",
"roleId",
COUNT(*) AS cnt,
MIN(id) AS keep_id,
ARRAY_AGG(id ORDER BY id) AS ids
FROM base_sys_user_role
WHERE deleted_at IS NULL
GROUP BY "userId", "roleId"
HAVING COUNT(*) > 1
ORDER BY cnt DESC, "userId", "roleId";
-- 2. 删除重复数据
DELETE FROM base_sys_user_role a
USING base_sys_user_role b
WHERE a."userId" = b."userId"
AND a."roleId" = b."roleId"
AND a.deleted_at IS NULL
AND b.deleted_at IS NULL
AND a.id > b.id;
-- 3. 执行后复查应返回 0
SELECT
"userId",
"roleId",
COUNT(*) AS cnt
FROM base_sys_user_role
WHERE deleted_at IS NULL
GROUP BY "userId", "roleId"
HAVING COUNT(*) > 1;
-- 唯一约束统一在 约束类.sql 中维护