Multiple Updates in MySQL

前端 未结 17 1420
南方客
南方客 2020-11-22 01:31

I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

Edit: For example I have the followi

17条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 01:55

    All of the following applies to InnoDB.

    I feel knowing the speeds of the 3 different methods is important.

    There are 3 methods:

    1. INSERT: INSERT with ON DUPLICATE KEY UPDATE
    2. TRANSACTION: Where you do an update for each record within a transaction
    3. CASE: In which you a case/when for each different record within an UPDATE

    I just tested this, and the INSERT method was 6.7x faster for me than the TRANSACTION method. I tried on a set of both 3,000 and 30,000 rows.

    The TRANSACTION method still has to run each individually query, which takes time, though it batches the results in memory, or something, while executing. The TRANSACTION method is also pretty expensive in both replication and query logs.

    Even worse, the CASE method was 41.1x slower than the INSERT method w/ 30,000 records (6.1x slower than TRANSACTION). And 75x slower in MyISAM. INSERT and CASE methods broke even at ~1,000 records. Even at 100 records, the CASE method is BARELY faster.

    So in general, I feel the INSERT method is both best and easiest to use. The queries are smaller and easier to read and only take up 1 query of action. This applies to both InnoDB and MyISAM.

    Bonus stuff:

    The solution for the INSERT non-default-field problem is to temporarily turn off the relevant SQL modes: SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,"STRICT_TRANS_TABLES",""),"STRICT_ALL_TABLES",""). Make sure to save the sql_mode first if you plan on reverting it.

    As for other comments I've seen that say the auto_increment goes up using the INSERT method, this does seem to be the case in InnoDB, but not MyISAM.

    Code to run the tests is as follows. It also outputs .SQL files to remove php interpreter overhead

    \n";
    
        file_put_contents("./$TestName.sql", implode(";\n", $TheQueries).';');
    }
    

提交回复
热议问题