guoyu/log/修正学生角色分配.sql
2025-12-11 23:28:07 +08:00

71 lines
2.2 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.

-- ========================================
-- 修正学生角色分配
-- ========================================
-- 问题71个学生有班级但没有"学员"角色
-- 影响:统计学生数时不准确
-- 解决:给所有有班级的学生添加"学员"角色
-- ========================================
-- 第1步查询学员角色ID
SELECT role_id, role_name, role_key
FROM sys_role
WHERE role_name LIKE '%学员%' OR role_key LIKE '%student%';
-- 假设学员角色ID为4请根据实际情况修改
SET @student_role_id = 4;
-- 第2步查询需要添加角色的学生
SELECT
u.user_id,
u.user_name,
u.nick_name,
'需要添加学员角色' as action
FROM sys_user u
INNER JOIN student_class sc ON u.user_id = sc.student_id
LEFT JOIN sys_user_role ur ON u.user_id = ur.user_id AND ur.role_id = @student_role_id
WHERE ur.user_id IS NULL
LIMIT 10;
-- 统计数量
SELECT COUNT(DISTINCT u.user_id) as need_role_count
FROM sys_user u
INNER JOIN student_class sc ON u.user_id = sc.student_id
LEFT JOIN sys_user_role ur ON u.user_id = ur.user_id AND ur.role_id = @student_role_id
WHERE ur.user_id IS NULL;
-- 第3步批量添加学员角色
INSERT INTO sys_user_role (user_id, role_id)
SELECT DISTINCT
u.user_id,
@student_role_id
FROM sys_user u
INNER JOIN student_class sc ON u.user_id = sc.student_id
LEFT JOIN sys_user_role ur ON u.user_id = ur.user_id AND ur.role_id = @student_role_id
WHERE ur.user_id IS NULL;
-- 第4步验证结果
SELECT
'有班级的学生' as type,
COUNT(DISTINCT student_id) as count
FROM student_class
UNION ALL
SELECT
'有学员角色的用户' as type,
COUNT(DISTINCT u.user_id) as count
FROM sys_user u
INNER JOIN sys_user_role ur ON u.user_id = ur.user_id
INNER JOIN sys_role r ON ur.role_id = r.role_id
WHERE r.role_name LIKE '%学员%';
-- 应该显示两个数字一致都是278
-- ========================================
-- 使用说明
-- ========================================
-- 1. 先查询学员角色ID第1步
-- 2. 修改@student_role_id为实际ID
-- 3. 查询需要添加角色的学生第2步确认
-- 4. 执行批量添加第3步
-- 5. 验证结果第4步
-- ========================================