Files
ccdi/doc/数据库文档/员工调动记录/04_add_unique_index.sql
2026-02-11 10:42:38 +08:00

24 lines
1.1 KiB
SQL
Raw Permalink 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.
-- =============================================
-- 员工调动记录唯一性约束
-- 功能说明:根据 员工ID + 调动前部门ID + 调动后部门ID + 调动日期 创建唯一索引
-- 创建时间2026-02-11
-- =============================================
-- 1. 检查并清理现有重复数据(保留最早创建的记录)
DELETE t1 FROM ccdi_staff_transfer t1
INNER JOIN ccdi_staff_transfer t2
WHERE t1.staff_id = t2.staff_id
AND t1.dept_id_before = t2.dept_id_before
AND t1.dept_id_after = t2.dept_id_after
AND t1.transfer_date = t2.transfer_date
AND t1.id > t2.id;
-- 2. 添加唯一索引
-- 创建唯一索引MySQL不支持 DROP INDEX IF EXISTS 语法)
CREATE UNIQUE INDEX uk_staff_transfer_date ON ccdi_staff_transfer (staff_id, dept_id_before, dept_id_after, transfer_date);
-- 执行结果说明
-- 1. 第一条SQL会删除重复数据只保留每组重复数据中ID最小的记录最早创建的
-- 2. 第二条SQL删除可能存在的旧索引
-- 3. 第三条SQL创建唯一索引确保后续不会再插入重复数据