优化 MySQL 阻止我的后端事务的存储过程
Optimize MySQL stored procedure that is blocking my back-end transactions
我有这个简单的存储过程,每天执行一次,根据用户拥有的材料数量更新用户的“能量”。但这需要大约 2 分钟才能结束,我想知道是否有更好的方法:
BEGIN
SET @energy_premium = 10;
SET @energy_free = 5;
UPDATE user
SET energy = @energy_premium
WHERE id IN (
SELECT fk_user
FROM material
GROUP BY fk_user
HAVING COUNT(fk_user)>=2 AND user.id = material.fk_user);
UPDATE user
SET energy = @energy_free
WHERE id IN (
SELECT fk_user
FROM material
GROUP BY fk_user
HAVING COUNT(fk_user)=1 AND user.id = material.fk_user);
END
此外,当此存储过程正在执行时,我的后端服务无法对数据库进行事务处理。
测试一下:
BEGIN
SET @energy_premium = 10;
SET @energy_free = 5;
UPDATE user
JOIN ( SELECT fk_user, CASE COUNT(fk_user) WHEN 1
THEN @energy_free
ELSE @energy_premium
END energy
FROM material
GROUP BY fk_user ) mat ON user.id = mat.fk_user
SET user.energy = mat.energy;
END;
我有这个简单的存储过程,每天执行一次,根据用户拥有的材料数量更新用户的“能量”。但这需要大约 2 分钟才能结束,我想知道是否有更好的方法:
BEGIN
SET @energy_premium = 10;
SET @energy_free = 5;
UPDATE user
SET energy = @energy_premium
WHERE id IN (
SELECT fk_user
FROM material
GROUP BY fk_user
HAVING COUNT(fk_user)>=2 AND user.id = material.fk_user);
UPDATE user
SET energy = @energy_free
WHERE id IN (
SELECT fk_user
FROM material
GROUP BY fk_user
HAVING COUNT(fk_user)=1 AND user.id = material.fk_user);
END
此外,当此存储过程正在执行时,我的后端服务无法对数据库进行事务处理。
测试一下:
BEGIN
SET @energy_premium = 10;
SET @energy_free = 5;
UPDATE user
JOIN ( SELECT fk_user, CASE COUNT(fk_user) WHEN 1
THEN @energy_free
ELSE @energy_premium
END energy
FROM material
GROUP BY fk_user ) mat ON user.id = mat.fk_user
SET user.energy = mat.energy;
END;