-- ============================================= -- 添加 study_info 表的唯一约束 -- 确保同一机构不会有相同的 study_instance_uid -- 日期:2025-12-30 -- ============================================= USE qconline; -- ============================================= -- 第一步:查看当前重复数据 -- ============================================= SELECT '=== 检查是否有重复的 study_instance_uid ===' AS ''; SELECT institution_id, study_instance_uid, COUNT(*) as count, GROUP_CONCAT(study_id) as study_ids, GROUP_CONCAT(id) as ids, MIN(create_time) as first_created, MAX(create_time) as last_created FROM study_info GROUP BY institution_id, study_instance_uid HAVING COUNT(*) > 1; -- ============================================= -- 第二步:添加唯一约束 -- ============================================= SELECT '=== 添加唯一约束 ===' AS ''; -- 删除可能存在的旧约束(如果有) ALTER TABLE study_info DROP INDEX IF EXISTS uk_study_instance; -- 添加新的唯一约束(institution_id + study_instance_uid) ALTER TABLE study_info ADD UNIQUE KEY uk_study_instance (institution_id, study_instance_uid); -- ============================================= -- 第三步:验证约束 -- ============================================= SELECT '=== 验证约束是否添加成功 ===' AS ''; SHOW INDEX FROM study_info WHERE Key_name = 'uk_study_instance'; -- ============================================= -- 说明 -- ============================================= /* 1. 约束说明: - 约束名称:uk_study_instance - 约束字段:institution_id + study_instance_uid - 作用:防止同一机构产生重复的 study_instance_uid 记录 2. 如果执行失败: - 说明存在重复数据,需要先执行清理脚本(见 cleanup_duplicate_studies.sql) - 清理完成后再执行本脚本 3. 代码层面的处理: - uploadAndParse(): 使用 selectList 检查,取第一条并警告 - processStudyWithTransaction(): 使用 selectList 检查,更新已存在记录 - 如果检测到多条记录,会在日志中记录警告 4. 建议: - 执行本脚本前,先查看重复数据 - 确认重复数据是否需要保留 - 如果不需要,执行清理脚本 */