xiangyixiangqin/server/cleanup_duplicate_views.sql
2026-01-28 18:52:35 +08:00

25 lines
640 B
SQL
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.

-- 清理 UserView 表中的重复记录
-- 保留每对用户UserId + TargetUserId的最新一条记录
-- 首先查看有多少重复记录
SELECT UserId, TargetUserId, COUNT(*) as cnt
FROM UserView
GROUP BY UserId, TargetUserId
HAVING COUNT(*) > 1;
-- 删除重复记录,保留 Id 最大的那条(即最新的)
DELETE FROM UserView
WHERE Id NOT IN (
SELECT MaxId FROM (
SELECT MAX(Id) as MaxId
FROM UserView
GROUP BY UserId, TargetUserId
) AS KeepRecords
);
-- 验证清理结果
SELECT UserId, TargetUserId, COUNT(*) as cnt
FROM UserView
GROUP BY UserId, TargetUserId
HAVING COUNT(*) > 1;