Multiple Updates in MySQL

前端 未结 17 1442
南方客
南方客 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:58

    Why does no one mention multiple statements in one query?

    In php, you use multi_query method of mysqli instance.

    From the php manual

    MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

    Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found here which is based on answer from @Dakusan

    Transaction: 5.5194580554962
    Insert: 0.20669293403625
    Case: 16.474853992462
    Multi: 0.0412278175354

    As you can see, multiple statements query is more efficient than the highest answer.

    If you get error message like this:

    PHP Warning:  Error while sending SET_OPTION packet
    

    You may need to increase the max_allowed_packet in mysql config file which in my machine is /etc/mysql/my.cnf and then restart mysqld.

提交回复
热议问题