-- 插入触发器 CREATETRIGGER after_insert_user_group_map AFTER INSERTON user_group_map FOREACHROW BEGIN INSERTINTO group_user_count (group_id, user_count) VALUES (NEW.group_id, 1) ON DUPLICATE KEY UPDATE user_count = user_count +1; END;
-- 删除触发器 CREATETRIGGER after_delete_user_group_map AFTER DELETEON user_group_map FOREACHROW BEGIN UPDATE group_user_count SET user_count = user_count -1 WHERE group_id = OLD.group_id; END;
4. 预计算
在插入、删除或更新用户组映射时,预先计算并存储用户数量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
-- 更新触发器 CREATETRIGGER before_insert_user_group_map BEFORE INSERTON user_group_map FOREACHROW BEGIN SET@group_id = NEW.group_id; SET@user_count = (SELECTCOUNT(*) FROM user_group_map WHERE group_id =@group_id) +1; INSERTINTO group_user_count (group_id, user_count) VALUES (@group_id, @user_count) ON DUPLICATE KEY UPDATE user_count =@user_count; END;
CREATETRIGGER before_delete_user_group_map BEFORE DELETEON user_group_map FOREACHROW BEGIN SET@group_id = OLD.group_id; SET@user_count = (SELECTCOUNT(*) FROM user_group_map WHERE group_id =@group_id) -1; UPDATE group_user_count SET user_count =@user_count WHERE group_id =@group_id; END;
5. 使用ORM和批量查询
如果你使用的是ORM(例如SQLAlchemy),可以进行批量查询并将结果映射到用户组列表中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from sqlalchemy.orm import aliased from sqlalchemy.sql import func
Group = aliased(Group) UserGroupMap = aliased(UserGroupMap)