AgileBoot-Back-End/sql/fix_user_template_unique_constraint.sql

17 lines
842 B
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.

-- 修复用户模板表的唯一约束问题
-- 解决逻辑删除与唯一约束的冲突
-- 1. 删除原有的唯一约束
ALTER TABLE `user_template` DROP INDEX `uk_user_template_name`;
-- 2. 创建条件唯一索引,只对未删除的记录生效
-- MySQL 5.7+ 支持函数索引,但为了兼容性,我们使用另一种方案
-- 创建一个复合索引,对于已删除的记录,使用 NULL 值来避免唯一约束
ALTER TABLE `user_template` ADD UNIQUE INDEX `uk_user_template_name_active` (`user_id`, `template_name`, (CASE WHEN deleted = 0 THEN 0 ELSE NULL END));
-- 注意:这个索引允许以下情况:
-- - 用户A有模板"test1"deleted=0正常- 唯一
-- - 用户A有多个模板"test1"deleted=1已删除- 允许多个
-- 但不允许:
-- - 用户A有两个模板"test1"都是deleted=0