-- ========================================
-- 修复 pid=0 问题并添加外键约束
-- ========================================

-- 步骤 1: 将所有 pid=0 的记录改为 NULL（表示顶级分组）
UPDATE evaluation_point_groups
SET pid = NULL
WHERE pid = 0;

-- 验证修改结果
SELECT COUNT(*) as "顶级分组数量（pid为NULL）"
FROM evaluation_point_groups
WHERE pid IS NULL;

-- 步骤 2: 添加外键约束

-- 2.1 为 evaluation_points 表添加外键约束
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.2 为 evaluation_point_groups 表添加自引用外键约束
-- pid 引用同一个表的 id（父子关系）
-- NULL 值表示顶级分组，不受外键约束限制
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 '评查点分组父子关系自引用外键约束（pid=NULL表示顶级分组）';

-- 步骤 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
    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;
