guoyu/log/添加外键约束-防止孤儿数据.sql
2025-12-11 23:28:07 +08:00

109 lines
3.0 KiB
SQL
Raw 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步检查当前是否有孤儿数据应该已清理
SELECT
'孤儿班级关联' AS type,
COUNT(*) AS count
FROM student_class sc
LEFT JOIN sys_user u ON sc.student_id = u.user_id
WHERE u.user_id IS NULL
UNION ALL
SELECT
'孤儿课程分配' AS type,
COUNT(*) AS count
FROM course_assignment ca
LEFT JOIN sys_user u ON ca.student_id = u.user_id
WHERE u.user_id IS NULL;
-- 如果有孤儿数据,先执行清理脚本!
-- ========================================
-- 第2步添加外键约束
-- ========================================
-- 2.1 学生班级关联表
ALTER TABLE student_class
ADD CONSTRAINT fk_student_class_user
FOREIGN KEY (student_id)
REFERENCES sys_user(user_id)
ON DELETE CASCADE; -- 删除用户时自动删除班级关联
-- 2.2 课程分配表
ALTER TABLE course_assignment
ADD CONSTRAINT fk_assignment_student
FOREIGN KEY (student_id)
REFERENCES sys_user(user_id)
ON DELETE CASCADE; -- 删除用户时自动删除课程分配
-- 2.3 学习记录表
ALTER TABLE learning_record
ADD CONSTRAINT fk_learning_student
FOREIGN KEY (student_id)
REFERENCES sys_user(user_id)
ON DELETE CASCADE; -- 删除用户时自动删除学习记录
-- 2.4 学习记录详情表
ALTER TABLE learning_detail
ADD CONSTRAINT fk_detail_student
FOREIGN KEY (student_id)
REFERENCES sys_user(user_id)
ON DELETE CASCADE;
-- 2.5 考试记录表
ALTER TABLE exam_record
ADD CONSTRAINT fk_exam_student
FOREIGN KEY (student_id)
REFERENCES sys_user(user_id)
ON DELETE CASCADE;
-- 2.6 答题记录表
ALTER TABLE student_answer
ADD CONSTRAINT fk_answer_student
FOREIGN KEY (student_id)
REFERENCES sys_user(user_id)
ON DELETE CASCADE;
-- ========================================
-- 第3步验证外键约束
-- ========================================
SELECT
TABLE_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
DELETE_RULE
FROM information_schema.key_column_usage
WHERE table_schema = 'study'
AND referenced_table_name = 'sys_user'
AND constraint_name LIKE 'fk%';
-- 应该显示所有刚添加的外键约束
-- ========================================
-- 第4步测试外键约束
-- ========================================
-- 测试方法:
-- 1. 创建一个测试用户
-- 2. 给该用户分配班级、课程等
-- 3. 删除该用户
-- 4. 检查相关数据是否自动删除
-- ========================================
-- 使用说明
-- ========================================
-- 1. 先确认孤儿数据已清理第1步
-- 2. 执行第2步添加外键约束
-- 3. 执行第3步验证
-- 4. 以后删除用户时,相关数据会自动删除
-- 5. 不会再产生孤儿数据
-- 6. 课程分配人数 = 用户管理人数
-- ========================================