Sql Multiple Update Query making faster

Question

I have A query Like this.

UPDATE package
            SET DonePackageID = :NewDonePackageID ,UserId=:NewUserID
            where DonePackageID=:DonePackageID AND UserId=:UserID AND ConsumerID=:ConsumerID

I runned this code but just ConsumerID is changing. I write code like this

    for(i){
//Query dataBase
   " UPDATE package
            SET DonePackageID = :NewDonePackageID ,UserId=:NewUserID
            where DonePackageID=:DonePackageID AND UserId=:UserID AND ConsumerID=".ID[i]
    }

I Have 600.000 Data and when i runned this code my MYSQL server is runned about 2 Hours. How can i write better than query about my issue ? How can i running faster this query ?


Show source
| pdo   | php   | mysql   2017-01-07 14:01 1 Answers

Answers to Sql Multiple Update Query making faster ( 1 )

  1. 2017-01-07 15:01

    You do not want to loop through 600,000 rows and do a zillion updates. You want to do them all in one statement. Something like:

    UPDATE package p JOIN
           t
           ON t.DonePackageID = p.DonePackageID and
              t.userId = p.userId
        SET p.DonePackageID = t.NewDonePackageID,
            p.UserId = t.NewUserID;
    

    This assumes the correct columns in t (should be obvious).

    This will work best with an index on package(UserId, DonePackageId), even though this will slow the query down.

    Updating 600,000 rows (particularly with an update on the active index) can still be slow. You might want to do the updates in batches. One simple method is:

    UPDATE package p JOIN
           t
           ON t.DonePackageID = p.DonePackageID and
              t.userId = p.userId
        SET p.DonePackageID = t.NewDonePackageID,
            p.UserId = t.NewUserID
        WHERE p.DonePackageID <> t.NewDonePackageID OR
              p.UserId <> t.NewUserID
        LIMIT 1000;
    

    You can just run this until no more rows are updated.

Leave a reply to - Sql Multiple Update Query making faster

◀ Go back