Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optimize MySQL stored procedure that is blocking my back-end transactions

I have this simple stored procedure that executes once per day to update the "energy" of the users depending on how many materials they have. But this takes around 2 minutes to end and I am wondering if there is a better way to do it:

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

Also, when this stored procedure is executing my back-end services can’t make transactions to the database.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Test this:

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading