all in
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
-- ========================================
|
||||
-- 为评查点系统添加外键约束
|
||||
-- ========================================
|
||||
|
||||
-- 1️⃣ 为 evaluation_points 表添加外键约束
|
||||
-- evaluation_point_groups_id 引用 evaluation_point_groups.id
|
||||
ALTER TABLE evaluation_points
|
||||
ADD CONSTRAINT fk_evaluation_points_group
|
||||
FOREIGN KEY (evaluation_point_groups_id)
|
||||
REFERENCES evaluation_point_groups(id)
|
||||
ON DELETE SET NULL -- 删除分组时,将评查点的分组ID设为NULL
|
||||
ON UPDATE CASCADE; -- 更新分组ID时,级联更新
|
||||
|
||||
-- 2️⃣ 为 evaluation_point_groups 表添加自引用外键约束
|
||||
-- pid 引用同一个表的 id(父子关系)
|
||||
ALTER TABLE evaluation_point_groups
|
||||
ADD CONSTRAINT fk_evaluation_point_groups_parent
|
||||
FOREIGN KEY (pid)
|
||||
REFERENCES evaluation_point_groups(id)
|
||||
ON DELETE CASCADE -- 删除父分组时,级联删除子分组
|
||||
ON UPDATE CASCADE; -- 更新父分组ID时,级联更新
|
||||
|
||||
-- 添加注释
|
||||
COMMENT ON CONSTRAINT fk_evaluation_points_group ON evaluation_points IS '评查点所属分组外键约束';
|
||||
COMMENT ON CONSTRAINT fk_evaluation_point_groups_parent ON evaluation_point_groups IS '评查点分组父子关系自引用外键约束';
|
||||
|
||||
-- 验证外键约束是否创建成功
|
||||
SELECT
|
||||
tc.table_name,
|
||||
tc.constraint_name,
|
||||
kcu.column_name,
|
||||
ccu.table_name AS foreign_table_name,
|
||||
ccu.column_name AS foreign_column_name
|
||||
FROM information_schema.table_constraints AS tc
|
||||
JOIN information_schema.key_column_usage AS kcu
|
||||
ON tc.constraint_name = kcu.constraint_name
|
||||
AND tc.table_schema = kcu.table_schema
|
||||
JOIN information_schema.constraint_column_usage AS ccu
|
||||
ON ccu.constraint_name = tc.constraint_name
|
||||
AND ccu.table_schema = tc.table_schema
|
||||
WHERE tc.constraint_type = 'FOREIGN KEY'
|
||||
AND tc.table_name IN ('evaluation_points', 'evaluation_point_groups')
|
||||
ORDER BY tc.table_name, tc.constraint_name;
|
||||
Reference in New Issue
Block a user