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>
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
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!