If you are using MySql 8.0+ you can create a CTE that returns the rows of the ids that you want to update and their marks and join it to the table:

WITH cte(studentId, marks) AS (VALUES
  ROW(1, 25), ROW(2, 22), ROW(5, 27), ROW(7, 30), ROW(9, 24)
)
UPDATE tablename t
INNER JOIN cte c ON c.studentId = t.studentId
SET t.marks = c.marks

See the demo.

For previous versions, instead of the CTE you can join a query that uses UNION ALL:

UPDATE tablename t
INNER JOIN (
  SELECT 1 studentId, 25 marks UNION ALL
  SELECT 2, 22 UNION ALL
  SELECT 5, 27 UNION ALL
  SELECT 7, 30 UNION ALL
  SELECT 9, 24 
) c ON c.studentId = t.studentId
SET t.marks = c.marks

See the demo.

Answer from forpas on Stack Overflow
Top answer
1 of 2
2

If you are using MySql 8.0+ you can create a CTE that returns the rows of the ids that you want to update and their marks and join it to the table:

WITH cte(studentId, marks) AS (VALUES
  ROW(1, 25), ROW(2, 22), ROW(5, 27), ROW(7, 30), ROW(9, 24)
)
UPDATE tablename t
INNER JOIN cte c ON c.studentId = t.studentId
SET t.marks = c.marks

See the demo.

For previous versions, instead of the CTE you can join a query that uses UNION ALL:

UPDATE tablename t
INNER JOIN (
  SELECT 1 studentId, 25 marks UNION ALL
  SELECT 2, 22 UNION ALL
  SELECT 5, 27 UNION ALL
  SELECT 7, 30 UNION ALL
  SELECT 9, 24 
) c ON c.studentId = t.studentId
SET t.marks = c.marks

See the demo.

2 of 2
1

You could run one simple query five times, with different values:

UPDATE MyTable SET marks = ? WHERE studentId = ?

The idea is that you would write a loop in some application code, so you process the first element from each of your arrays. Then the second element of both arrays, and so on. For example in PHP:

$studentId = [1,2,5,7,9];

$marks = [25, 22, 27, 30, 24];

$stmt = $pdo->prepare("UPDATE MyTable SET marks = ? WHERE studentId = ?");

for (i<5; ++$i) {
  $stmt->execute([$marks[studentId[$i]]);
}

From its earliest versions, SQL was always intended to be used in combination with an application language. Other languages have variables and loops and conditions and functions, which complement SQL. The easiest solution is to use these languages together.

If you really want to write a single UPDATE statement to update all five, it's possible, but it's really not as clear.

UPDATE MyTable
SET marks = CASE studentId
            WHEN 1 THEN 25
            WHEN 2 THEN 22
            WHEN 5 THEN 27
            WHEN 7 THEN 30
            WHEN 9 THEN 24
            END
WHERE studentId IN (1,2,5,7,9);

There are other clever ways of doing it in one statement, but all these solutions are hard to modify or maintain. They are needlessly complex.

I recommend doing it the simple way.

Discussions

mysql - Update multiple rows using for loop and array php - Stack Overflow
$id1=array($aa1,$aa2,$aa3,$aa4,$aa5,$aa6,$aa7); $rank1=array($a1,$a4,$a7,$a10,$a13,$a16,$a19); require_once("connection.php"); for($i=0;$i<7;$i++){ $sql = "update live_tracking set swim_rank = '"$rank1[$i]."' where id = '".$id1[$i]."'"; } I want to update multiple rows of my mysql database ... More on stackoverflow.com
🌐 stackoverflow.com
PHP MYSQL updating multiple rows using values from an array - Stack Overflow
I've working on this problem for a while, and I've been stuck for a few days. What I have is a basic blog system, and right now I'm stuck on trying to delete/hide posts from a list. if(isset($_POST[' More on stackoverflow.com
🌐 stackoverflow.com
March 21, 2013
mysql - Updating multiple rows with different values in one query - Database Administrators Stack Exchange
I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand. For instance, two update... More on dba.stackexchange.com
🌐 dba.stackexchange.com
June 28, 2014
Mysql JSON update multiple object values in an array - Database Administrators Stack Exchange
How can I update the interests if there are multiple values to be updated? Running the above update statement to update the Visual Arts interest results in an error: Query 1 ERROR: Invalid JSON path expression. The error is around character position 1. I assume it's because there are two paths returned from ... More on dba.stackexchange.com
🌐 dba.stackexchange.com
🌐
SitePoint
sitepoint.com › php
How to update multiple rows with an array - PHP - SitePoint Forums | Web Development & Design Community
July 23, 2019 - I am trying to update a SQL table ... my Code. $property_img[]=$image; if (empty($property_img)){ return null;} $count=Count($property_img); if(Count($property_img)===0) { var_dump($count); $property_img=$property_img[0]; ...
🌐
DEV Community
dev.to › azophy › how-to-update-multiple-rows-based-on-list-of-key-val-pairs-in-mysql-mariadb-postgresql-4lpp
How to update multiple rows based on list of key-val pairs (in MySQL, MariaDB, & PostgreSQL) - DEV Community
September 29, 2023 - UPDATE table_name SET changed_col = temp_data.column1 FROM (VALUES ROW('key1', 'val1'), ROW('key2', 'val2'), .... ) as temp_data WHERE comparison_col = temp_data.column0 · https://dev.mysql.com/doc/refman/8.0/en/values.html
🌐
TutorialsPoint
tutorialspoint.com › update-multiple-rows-in-a-single-column-in-mysql
Update multiple rows in a single column in MySQL?
To update multiple rows in a single column, use CASE statement. Let us first create a table − · mysql> create table updateMultipleRowsDemo -> ( -> StudentId int, -> StudentMathScore int -> ); Query OK, 0 rows affected (0.63 sec)
🌐
MySQL
forums.mysql.com › read.php
Updating multiple rows with an array using PHP with mySQLi
September 15, 2009 - Forum for building directly from the source code.
🌐
Stack Overflow
stackoverflow.com › questions › 15513353 › php-mysql-updating-multiple-rows-using-values-from-an-array
PHP MYSQL updating multiple rows using values from an array - Stack Overflow
March 21, 2013 - $checked = array ( 0 => 10, 1 => 8, 2 => 4 ); //print_r($checked); $hide_post = 'UPDATE post SET hide_post=1 WHERE post_id IN (' . implode(',', array_map('intval', $checked)) . ')'; echo $hide_post; ... Run the same query in phpmyadmin and check whether the same query returns ant error or not. ... @BrianBaker Check your database connection and also check you included necessary database file in your php file ... The db is included at the start of the file as $db. The posts are pulled from the database using the same connection, so I'd imagine updating the database would work as well.
Find elsewhere
🌐
DaniWeb
daniweb.com › programming › web-development › threads › 35096 › updating-multiple-rows-with-one-form
php - updating multiple rows with one form | DaniWeb
September 23, 2015 - Player ID: $player_id "); } } else { $tp=$n2m*2+$n3m*3+$nfm; $ppg=$tp/$ngp; $insert=mysql_query("INSERT INTO pstats(2m, 3m, fm, tfouls, gplayed, tp, ppg, player_id) VALUES('$n2m','$n3m','$nfm','$ntf','$ngp','$tp','$ppg','$id')"); $updateppg=mysql_query("UPDATE player SET ppg='$ppg' WHERE player_id='$id'"); if(!$update) { die("Could not save the record! Player ID: $player_id "); } } } break; // Default case: choose a team default: //teams dropdown menu $sql="SELECT * FROM teams"; $result=mysql_query($sql); $num_results = mysql_num_rows($result); $options=""; for ($i=0; $i<$num_results; $i++) {
🌐
Quora
quora.com › How-can-you-update-multiple-records-in-MySQL-with-one-query
How to update multiple records in MySQL with one query - Quora
Syntax (MySQL 8+ supports VALUES() in derived table or use UNION SELECT): UPDATE target JOIN ( SELECT 1 AS id, 'value1' AS new_val UNION ALL SELECT 2, 'value2' UNION ALL SELECT 3, 'value3' ) AS src ON target.id = src.id SET target.col_to_change ...
Top answer
1 of 1
2

Here's my experimental attempt, though it fails. I'm posting this because you asked to see what I had tried. I don't claim this is a full solution to your question.

drop table if exists mytable;

create table mytable (
  id serial primary key,
  meta json
);

insert into mytable set meta = '...your example data...';

SELECT mytable.id, j.*
FROM mytable CROSS JOIN JSON_TABLE(
  mytable.meta,
  '$.industries[*]' COLUMNS(
    industry_num FOR ORDINALITY,
    industry_name VARCHAR(20) PATH '$.name',
    NESTED PATH '$.interests[*]' COLUMNS(
      interest_num FOR ORDINALITY,
      interest_name VARCHAR(20) PATH '$.name'
    )
  )
) AS j;

Output:

+----+--------------+---------------+--------------+---------------+
| id | industry_num | industry_name | interest_num | interest_name |
+----+--------------+---------------+--------------+---------------+
|  1 |            1 | Science       |            1 | Visual Arts   |
|  1 |            1 | Science       |            2 | Data Science  |
|  1 |            2 | Arts          |            1 | Music         |
|  1 |            2 | Arts          |            2 | Visual Arts   |
+----+--------------+---------------+--------------+---------------+

Now that we have a method for identifying the array index at each level of the JSON nested objects, we can try to UPDATE the value:

WITH cte AS (
  SELECT mytable.id, j.*
  FROM mytable CROSS JOIN JSON_TABLE(
    mytable.meta,
    '$.industries[*]' COLUMNS(
      industry_num FOR ORDINALITY,
      industry_name VARCHAR(20) PATH '$.name',
      NESTED PATH '$.interests[*]' COLUMNS(
        interest_num FOR ORDINALITY,
        interest_name VARCHAR(20) PATH '$.name'
      )
    )
  ) AS j
)
UPDATE mytable JOIN cte USING (id)
SET meta = JSON_REPLACE(meta, CONCAT('$.industries[', cte.industry_num-1, '].interests[', cte.interest_num-1, '].name'), 'New Interest Name')
WHERE cte.interest_name = 'Visual Arts';

The problem that I have not solved is that this appears to only do one replacement.

JSON_REPLACE() takes variable arguments, so you can change the value at more than one path, but constructing that call would require dynamic SQL. I'm not interested in doing any more work on this, because in my opinion, the work above should demonstrate that managing this data in JSON is already more trouble than it's worth.

Top answer
1 of 2
1

Finally i got it, after several tries i manage to get what i needed, so i'll share my answer.

First i made one procedure to update one single row in the column:

delimiter //
create procedure update_amount_products (in id int)
begin
update categories set products_amount= 
           (SELECT DISTINCT COUNT( products_to_categories.products_id ) 
FROM categories_description
INNER JOIN products_to_categories ON products_to_categories.categories_id = categories_description.categories_id
INNER JOIN products_description ON products_description.products_id = products_to_categories.products_id
WHERE categories_description.categories_id =id)
WHERE categories_id = id;
end
//

DELIMITER ;

Then i realized i could handle the whole column by calling the procedure with another procedure with a loop on it

DELIMITER $$
CREATE PROCEDURE update_products_amount()

   BEGIN
      DECLARE a INT Default 1 ;
      DECLARE category_length int;

      select max(categories_id) into category_length from categories_description;

      simple_loop: LOOP
         SET a=a+1;

         call update_amount_products(a);

         IF a >= category_length THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$
DELIMITER ;

commit;

Finally, all i have to do now, is to call my last procedure and voilá, all my column will be automatically updated.

call update_products_amount();
2 of 2
0

Not quite sure what you are trying to achieve bit the UPDATE statement would appear to do the job

To update a single known product:

UPDATE PRODUCTS SET PRODUCT_AMOUNT = 42 WHERE PRODUCTS_ID = 1

You can update several at once depending on the WHERE clause and you can also set it to a value from another table.

🌐
Reddit
reddit.com › r/phphelp › mysql - how can i insert multiple rows with insert on update
r/PHPhelp on Reddit: MySql - How can I insert multiple rows with INSERT ON UPDATE
August 31, 2024 -

Hello,

Been stuck on this one for a while.

Using Mysqli, how can I insert (or update if the key already exists) multiple rows in one transaction?

I would like to loop over this array and execute the query only once, instead of on each iteration of the loop

foreach($challengeData as $challengeId => $status) {



    $this->conn->execute_query('
          INSERT INTO my_table
          (
             challenge_id,
             status
    
          )
          
          VALUES
          (
             ?,?
          )
          
          ON DUPLICATE KEY UPDATE 
             status = VALUES(status)
       ',
       [
          $challengeId,
          $status
       ]
    );



}
🌐
Post.Byes
post.bytes.com › home › forum › topic › php
How to update multiple rows (php/mysql) for little league database - Post.Byes
So your POST variable can be an array of arrays. As far as I can see that looping should work, however, I am a bit too busy to try it myself at the moment. ** Where is $count set? I didn't mean to insult you, but there is not variable assignment in the code you posted. So I am guessing that you have not posted it all? I will share some logic of how I would set up your page: ... if (page request is from submitting a form) { Go through and validate $_POST and update MySQL table with values Set $message = "Table successfully updated"; } Call data from MySQL table Print HTML and make the form submit to the current page if (isset($message)) { echo $message; } That way, there is no header changes, your update code only runs if a form was submitted, but the rest of the page loads the same all the time.
🌐
Edmondscommerce
edmondscommerce.github.io › mysql › very-high-speed-batch-update-multiple-rows-of-a-table-in-single-query.html
Very High Speed Batch Update Multiple Rows of a Table in Single Query ·
October 13, 2011 - function bulkUpdateSingleColumn($table, $id_column, $update_column, array &$idstovals){ $sql = "update $table set $update_column = CASE $id_column "; foreach($idstovals as $id=>$val){ $sql .= " WHEN '$id' THEN '$val' \n"; } $sql .= " END WHERE $id_column in (" . implode(',', array_keys($idstovals)) . ")"; //debugging info echo '<small>'.$sql.'</small>'; $idstovals=array(); db_query($sql); done(); } Tags: mysqlperformancephpfunctiontablebulkecommerceupdatetiprows