-- ============================================
-- 清理已删除用户的档案数据
-- 用途：解决"信息编号已存在"但列表中看不到的问题
-- 日期：2024-12-02
-- ============================================

-- 第一步：查看要删除的数据（确认）
SELECT 
    p.profile_id AS '档案ID',
    p.info_number AS '信息编号',
    p.user_id AS '关联用户ID',
    u.user_name AS '用户账号',
    u.del_flag AS '删除标记',
    CASE 
        WHEN u.user_id IS NULL THEN '用户不存在'
        WHEN u.del_flag = '2' THEN '用户已删除'
        ELSE '正常'
    END AS '状态',
    p.create_time AS '创建时间'
FROM psy_user_profile p
LEFT JOIN sys_user u ON p.user_id = u.user_id
WHERE u.del_flag = '2' OR u.user_id IS NULL
ORDER BY CAST(p.info_number AS UNSIGNED);

-- 第二步：备份要删除的数据（可选但推荐）
CREATE TABLE IF NOT EXISTS psy_user_profile_deleted_backup_20241202 AS
SELECT p.* 
FROM psy_user_profile p
LEFT JOIN sys_user u ON p.user_id = u.user_id
WHERE u.del_flag = '2' OR u.user_id IS NULL;

-- 第三步：删除已删除用户的档案
DELETE p FROM psy_user_profile p
LEFT JOIN sys_user u ON p.user_id = u.user_id
WHERE u.del_flag = '2' OR u.user_id IS NULL;

-- 查看删除结果
SELECT CONCAT('已删除 ', ROW_COUNT(), ' 条档案数据') AS '执行结果';

-- ============================================
-- 如果只想删除特定信息编号的档案（如114）
-- ============================================
-- DELETE FROM psy_user_profile WHERE info_number = '114';
