Home > Database > Mysql Tutorial > How Can I Update Multiple MySQL Rows with Different Values Using a Single Query?

How Can I Update Multiple MySQL Rows with Different Values Using a Single Query?

Linda Hamilton
Release: 2025-01-17 11:01:09
Original
914 people have browsed it

How Can I Update Multiple MySQL Rows with Different Values Using a Single Query?

Efficiently Updating Multiple MySQL Rows with Varied Values

This guide addresses the common challenge of updating multiple database rows with unique values using a single MySQL query. While several methods exist, this approach offers clarity and efficiency.

A Clearer Approach Using CASE Statements

The conventional method, often involving nested IF() statements, becomes cumbersome with multiple conditions. A superior alternative leverages the power of CASE statements:

<code class="language-sql">UPDATE table_users
SET cod_user = (CASE WHEN user_role = 'student' THEN '622057'
                     WHEN user_role = 'assistant' THEN '2913659'
                     WHEN user_role = 'admin' THEN '6160230'
                END),
    date = '12082014'
WHERE user_role IN ('student', 'assistant', 'admin') AND
      cod_office = '17389551';</code>
Copy after login

This streamlined query uses CASE to dynamically assign cod_user values based on user_role, while simultaneously setting date to a consistent value for all matching rows.

Key Considerations

  • CASE Statements: These provide a concise way to handle multiple conditional assignments within a single query.
  • WHERE Clause: This precisely targets rows for updating, ensuring only relevant records are modified.
  • Data Integrity: For optimal data management, store dates using MySQL's native date/time data types.

This combined CASE and WHERE approach offers a structured and easily understandable solution for updating multiple rows with diverse values in MySQL.

The above is the detailed content of How Can I Update Multiple MySQL Rows with Different Values Using a Single Query?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template