-- ========================================
-- 清理重复测评记录
-- 每个用户对每个量表只保留最新的一条记录
-- 创建时间: 2025-12-02
-- ========================================

-- 第一步：查看重复记录情况
SELECT 
    user_id,
    scale_id,
    COUNT(*) as record_count,
    GROUP_CONCAT(assessment_id ORDER BY assessment_id DESC) as assessment_ids,
    GROUP_CONCAT(status) as statuses
FROM psy_assessment
WHERE user_id IS NOT NULL
GROUP BY user_id, scale_id
HAVING COUNT(*) > 1
ORDER BY record_count DESC;

-- 第二步：查看将要删除的记录（预览）
SELECT a.* 
FROM psy_assessment a
WHERE a.assessment_id NOT IN (
    SELECT MAX(t.assessment_id) 
    FROM psy_assessment t 
    WHERE t.user_id IS NOT NULL
    GROUP BY t.user_id, t.scale_id
)
AND a.user_id IS NOT NULL
ORDER BY a.user_id, a.scale_id, a.assessment_id;

-- 第三步：备份将要删除的记录
CREATE TABLE IF NOT EXISTS psy_assessment_backup_duplicate AS
SELECT a.* 
FROM psy_assessment a
WHERE a.assessment_id NOT IN (
    SELECT MAX(t.assessment_id) 
    FROM psy_assessment t 
    WHERE t.user_id IS NOT NULL
    GROUP BY t.user_id, t.scale_id
)
AND a.user_id IS NOT NULL;

-- 验证备份
SELECT COUNT(*) AS '备份的重复记录数' FROM psy_assessment_backup_duplicate;

-- 第四步：删除相关的答案记录
DELETE FROM psy_assessment_answer 
WHERE assessment_id IN (
    SELECT assessment_id FROM psy_assessment_backup_duplicate
);

-- 第五步：删除相关的因子得分记录
DELETE FROM psy_factor_score 
WHERE assessment_id IN (
    SELECT assessment_id FROM psy_assessment_backup_duplicate
);

-- 第六步：删除相关的预警记录
DELETE FROM psy_warning 
WHERE assessment_id IN (
    SELECT assessment_id FROM psy_assessment_backup_duplicate
);

-- 第七步：删除相关的报告记录
DELETE FROM psy_assessment_report 
WHERE assessment_id IN (
    SELECT assessment_id FROM psy_assessment_backup_duplicate
);

-- 第八步：删除重复的测评记录（只保留每个用户对每个量表的最新记录）
DELETE FROM psy_assessment 
WHERE assessment_id IN (
    SELECT assessment_id FROM psy_assessment_backup_duplicate
);

-- 第九步：验证清理结果
SELECT 
    user_id,
    scale_id,
    COUNT(*) as record_count
FROM psy_assessment
WHERE user_id IS NOT NULL
GROUP BY user_id, scale_id
HAVING COUNT(*) > 1;
-- 如果返回空结果，说明清理成功

-- 第十步：查看清理后的记录数
SELECT COUNT(*) AS '清理后的测评记录数' FROM psy_assessment;

-- ========================================
-- 如果需要恢复数据，执行以下语句：
-- ========================================
/*
INSERT INTO psy_assessment SELECT * FROM psy_assessment_backup_duplicate;
*/

-- ========================================
-- 清理完成后，可以删除备份表：
-- ========================================
/*
DROP TABLE IF EXISTS psy_assessment_backup_duplicate;
*/
