Bulk update mysql with where statement

MysqlSql UpdateBulk

Mysql Problem Overview


How to update mysql data in bulk ? How to define something like this :

UPDATE `table` 
WHERE `column1` = somevalues
SET  `column2` = othervalues

with somevalues like :

VALUES
	('160009'),
	('160010'),
	('160011');

and othervalues :

VALUES
	('val1'),
	('val2'),
	('val3');

maybe it's impossible with mysql ? a php script ?

Mysql Solutions


Solution 1 - Mysql

The easiest solution in your case is to use ON DUPLICATE KEY UPDATE construction. It works really fast, and does the job in easy way.

INSERT into `table` (id, fruit)
    VALUES (1, 'apple'), (2, 'orange'), (3, 'peach')
    ON DUPLICATE KEY UPDATE fruit = VALUES(fruit);

or to use CASE construction

UPDATE table
SET column2 = (CASE column1 WHEN 1 THEN 'val1'
                 WHEN 2 THEN 'val2'
                 WHEN 3 THEN 'val3'
         END)
WHERE column1 IN(1, 2 ,3);

Solution 2 - Mysql

If the "bulk" data you have is dynamic and is coming from PHP (you did tag it, after all), then the query would look something like this:

INSERT INTO `foo` (id, bar)
VALUES 
	(1, 'pineapple'),
	(2, 'asian pear'),
	(5, 'peach')
ON DUPLICATE KEY UPDATE bar = VALUES(bar);

and the PHP to generate this from an existing array (assuming the array is of a format like:

$array = (
	somevalues_key => othervalues_value
);

) would look something like this (by no means the best (doesn't address escaping or sanitizing the values, for instance), just an quick example):

$pairs = array();
foreach ($array as $key => $value) {
	$pairs[] = "($key, '$value')";
}

$query = "INSERT INTO `foo` (id, bar) VALUES " . implode(', ', $pairs) . " ON DUPLICATE KEY UPDATE bar = VALUES(bar)";

Solution 3 - Mysql

If you are using a drag & drop tableView or collectionView to sort datas in your app, like allowing users to arrange their photos by drag and drop functionality, send a comma seperated list of ordered ids to the backend after user edits finish.

In your backend, explode ids to the an array like

$new_ranks = array();
$supplied_orders = explode(",", $_POST["supplied_new_order"]); //52,11,6,54,2 etc
$start_order = 99999;
foreach ($supplied_orders as $supplied_row_id) {
	//your all validations... make sure supplied_row_id belongs to that user or not etc..

    $new_ranks[intval($supplied_row_id)] = $start_order--;
}

now, you can update all new ranks like @Farside recommendation 2.

if (count($new_ranks) > 0) {
    $case_sqls = array(); 
    foreach ($new_ranks as $id => $rank) {
        $case_sqls[] = "WHEN ".intval($id)." THEN ".intval($rank)."";
    } 
    $case_sql = implode(" ", $case_sqls);

    $this->db->query("
        UPDATE 
            service_user_medias
        SET 
            rank = (CASE id ".$case_sql." END)
        WHERE 
            id IN(".implode(",", array_keys($new_ranks)).");
    ");
}

Solution 4 - Mysql

If you have data in array format then try this

and your query is like "UPDATE table WHERE column1 = ? SET column2 = ?"

then set it like below

foreach($data as $key => $value) {
    $query->bind_param('ss', $key, $value);
    $query->execute();
}

hope it'll work.

Reference from this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3673384View Question on Stackoverflow
Solution 1 - MysqlFarsideView Answer on Stackoverflow
Solution 2 - MysqlDavisView Answer on Stackoverflow
Solution 3 - MysqlwoherasView Answer on Stackoverflow
Solution 4 - MysqlVirusView Answer on Stackoverflow