guoyu/fix_duplicate_class.sql
2025-12-11 23:28:07 +08:00

72 lines
1.9 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.

-- ========================================
-- 修复学生多班级问题
-- ========================================
-- 第一步:查看有多个班级的学生
SELECT
student_id,
COUNT(*) as class_count,
GROUP_CONCAT(class_id ORDER BY join_time DESC) as class_ids,
GROUP_CONCAT(join_time ORDER BY join_time DESC) as join_times
FROM student_class
WHERE status = 1
GROUP BY student_id
HAVING COUNT(*) > 1;
-- 第二步查看编号206的详细记录
SELECT
sc.id,
sc.student_id,
sc.class_id,
c.class_name,
sc.status,
sc.join_time,
sc.create_time
FROM student_class sc
LEFT JOIN class c ON sc.class_id = c.id
WHERE sc.student_id = 206
ORDER BY sc.join_time DESC, sc.create_time DESC;
-- 第三步修复数据保留最新的班级记录其他设为status=0
-- ⚠️ 请先执行上面的查询确认数据后,再执行此更新!
-- 方法为每个学生只保留join_time最新的那条记录
UPDATE student_class sc1
SET status = 0
WHERE status = 1
AND student_id IN (
-- 找出有多个班级的学生
SELECT student_id
FROM (
SELECT student_id
FROM student_class
WHERE status = 1
GROUP BY student_id
HAVING COUNT(*) > 1
) AS multi_class_students
)
AND id NOT IN (
-- 为每个学生保留join_time最新的记录
SELECT id
FROM (
SELECT id
FROM student_class sc2
WHERE sc2.status = 1
AND sc2.student_id = sc1.student_id
ORDER BY sc2.join_time DESC, sc2.create_time DESC
LIMIT 1
) AS keep_records
);
-- 第四步:验证修复结果
SELECT
student_id,
COUNT(*) as active_class_count,
GROUP_CONCAT(class_id) as class_ids
FROM student_class
WHERE status = 1
GROUP BY student_id
HAVING COUNT(*) > 1;
-- 应该返回空结果,说明每个学生只有一个活跃班级