-- 清理观看历史重复数据
-- 保留每个用户对每个目标的最新一条记录

-- 1. 查看重复数据
SELECT 
    user_id,
    target_type,
    target_id,
    COUNT(*) as count
FROM eb_view_history
GROUP BY user_id, target_type, target_id
HAVING COUNT(*) > 1;

-- 2. 删除重复数据，保留最新的一条
DELETE FROM eb_view_history
WHERE id NOT IN (
    SELECT * FROM (
        SELECT MAX(id) as id
        FROM eb_view_history
        GROUP BY user_id, target_type, target_id
    ) AS temp
);

-- 3. 验证清理结果
SELECT 
    user_id,
    target_type,
    target_id,
    COUNT(*) as count
FROM eb_view_history
GROUP BY user_id, target_type, target_id
HAVING COUNT(*) > 1;

-- 4. 添加唯一索引，防止将来再次出现重复
ALTER TABLE eb_view_history 
ADD UNIQUE INDEX idx_user_target (user_id, target_type, target_id);
