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 following
Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
I want to combine all the following Updates into one query
UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
Why does no one mention multiple statements in one query?
In php, you use
multi_query
method of mysqli instance.From the php manual
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:
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.With PHP I did this. Use semicolon, split it into array and then submit via loop.
// You just building it in php like
So you can update hole table with one query
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.
Using your example:
Not sure why another useful option is not yet mentioned: