54 lines
1.9 KiB
SQL
54 lines
1.9 KiB
SQL
-- ========================================
|
|
-- 简化版外键约束(不需要自引用)
|
|
-- ========================================
|
|
|
|
-- 步骤 1: 将所有 pid=0 改为 NULL(标准做法)
|
|
UPDATE evaluation_point_groups
|
|
SET pid = NULL
|
|
WHERE pid = 0;
|
|
|
|
-- 步骤 2: 为 evaluation_points 添加外键约束
|
|
|
|
-- 2.1 子分组外键:evaluation_point_groups_id → evaluation_point_groups.id
|
|
ALTER TABLE evaluation_points
|
|
ADD CONSTRAINT fk_evaluation_points_child_group
|
|
FOREIGN KEY (evaluation_point_groups_id)
|
|
REFERENCES evaluation_point_groups(id)
|
|
ON DELETE SET NULL
|
|
ON UPDATE CASCADE;
|
|
|
|
-- 2.2 父分组外键:evaluation_point_groups_pid → evaluation_point_groups.id
|
|
ALTER TABLE evaluation_points
|
|
ADD CONSTRAINT fk_evaluation_points_parent_group
|
|
FOREIGN KEY (evaluation_point_groups_pid)
|
|
REFERENCES evaluation_point_groups(id)
|
|
ON DELETE SET NULL
|
|
ON UPDATE CASCADE;
|
|
|
|
-- ⚠️ 注意:不再需要 evaluation_point_groups 表的自引用外键
|
|
-- 因为 evaluation_points 已经直接存储了父级分组ID
|
|
|
|
-- 添加注释
|
|
COMMENT ON CONSTRAINT fk_evaluation_points_child_group ON evaluation_points
|
|
IS '评查点所属规则组外键约束(二级分组)';
|
|
|
|
COMMENT ON CONSTRAINT fk_evaluation_points_parent_group ON evaluation_points
|
|
IS '评查点类型外键约束(父级分组)';
|
|
|
|
-- 步骤 3: 验证外键约束是否创建成功
|
|
SELECT
|
|
tc.table_name AS "表名",
|
|
tc.constraint_name AS "约束名",
|
|
kcu.column_name AS "列名",
|
|
ccu.table_name AS "引用表名",
|
|
ccu.column_name AS "引用列名"
|
|
FROM information_schema.table_constraints AS tc
|
|
JOIN information_schema.key_column_usage AS kcu
|
|
ON tc.constraint_name = kcu.constraint_name
|
|
JOIN information_schema.constraint_column_usage AS ccu
|
|
ON ccu.constraint_name = tc.constraint_name
|
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
AND tc.table_name = 'evaluation_points'
|
|
AND kcu.column_name IN ('evaluation_point_groups_id', 'evaluation_point_groups_pid')
|
|
ORDER BY kcu.column_name;
|