The mysql update statement is simple. to update a field of a piece of data, write as follows:
Help
1 |
UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value' ; |
If the same field is updated to the same value, mysql is also very simple. modify where:
Help
1 |
UPDATE mytable SET myfield = 'value' WHERE other_field in ( 'other_values' ); |
Note that 'other _ values' is a comma (,)-separated string, for example, 1, 2, 3.
If multiple data entries are updated with different values, many may write as follows:
Help
1234 |
foreach ( $display_order as $id => $ordinal ) { $sql = "UPDATE categories SET display_order = $ordinal WHERE id = $id" ; mysql_query( $sql ); } |
It is an update record that repeats one by one. Update a record once, which has poor performance and can easily cause blocking.
Can I update an SQL statement in batches? Mysql does not provide a direct method for batch update, but it can be implemented with tips.
Help
1234567 |
UPDATE mytable SET myfield = CASE id WHEN 1 THEN 'value' WHEN 2 THEN 'value' WHEN 3 THEN 'value' END WHERE id IN (1,2,3) |
Here we use the case when tip to implement batch update.
For example:
Help
1234567 |
UPDATE categories SET display_order = CASE id WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 5 END WHERE id IN (1,2,3) |
This SQL statement indicates that the display_order field is updated. If id = 1, the value of display_order is 3. If id = 2, the value of display_order is 4, if id = 3, the value of display_order is 5.
The condition statements are written together.
The where part does not affect code execution, but it increases the SQL Execution efficiency. Make sure that the SQL statement only executes the number of rows to be modified. Here, only three rows of data are updated, and the where clause ensures that only three rows of data are executed.
If you want to update multiple values, you only need to slightly modify them:
Help
010203040506070809101112 |
UPDATE categories SET display_order = CASE id WHEN 1 THEN 3 WHEN 2 THEN 4 WHEN 3 THEN 5 END , title = CASE id WHEN 1 THEN 'New Title 1' WHEN 2 THEN 'New Title 2' WHEN 3 THEN 'New Title 3' END WHERE id IN (1,2,3) |
At this point, a mysql statement has been completed to update multiple records.
But to use it in the business, you need to combine the server language. Here we take php as an example to construct this mysql statement:
Help
0102030405060708091011121314151617 |
$display_order = array ( 1 => 4, 2 => 1, 3 => 2, 4 => 3, 5 => 9, 6 => 5, 7 => 8, 8 => 9 ); $ids = implode( ',' , array_keys ( $display_order )); $sql = "UPDATE categories SET display_order = CASE id " ; foreach ( $display_order as $id => $ordinal ) { $sql .= sprintf( "WHEN %d THEN %d " , $id , $ordinal ); } $sql .= "END WHERE id IN ($ids)" ; echo $sql ; |
In this example, eight records are updated. The code is easy to understand. Have you learned it?
Reference: http://www.ghugo.com/update-multiple-rows-with-different-values-and-a-single-sql-query/