-- 修改知识点表，将material_id设为必填字段
-- 执行日期：2025-09-27
-- 说明：将knowledge_points表的material_id字段从可选改为必填

-- 1. 首先检查是否有material_id为NULL的记录
SELECT COUNT(*) as null_count FROM knowledge_points WHERE material_id IS NULL AND is_deleted = FALSE;

-- 2. 如果有NULL值，需要先处理这些记录（可以删除或设置默认值）
-- 这里先删除material_id为NULL的记录（如果有的话）
DELETE FROM knowledge_points WHERE material_id IS NULL;

-- 3. 修改字段为NOT NULL，并修改外键约束
ALTER TABLE knowledge_points 
MODIFY COLUMN material_id INT NOT NULL COMMENT '关联资料ID';

-- 4. 删除旧的外键约束
ALTER TABLE knowledge_points 
DROP FOREIGN KEY knowledge_points_ibfk_2;

-- 5. 添加新的外键约束（CASCADE删除）
ALTER TABLE knowledge_points 
ADD CONSTRAINT knowledge_points_ibfk_2 
FOREIGN KEY (material_id) REFERENCES course_materials(id) ON DELETE CASCADE;

-- 6. 验证修改结果
DESCRIBE knowledge_points;
