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

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

Patricia Arquette
Release: 2025-01-17 11:17:14
Original
219 people have browsed it

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

Efficiently Updating Multiple MySQL Rows with Varying Values

MySQL offers several methods for updating multiple rows with distinct values in a single query. While IF statements can work, the CASE statement provides a more concise and readable solution, especially when dealing with multiple conditions.

Let's consider a scenario where we need to update the table_users table, assigning different cod_user values based on user roles within a specific office. A cleaner approach than using multiple IF statements is demonstrated below:

This query utilizes the CASE statement to update cod_user based on user_rol:

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

Here's a breakdown:

  • CASE statement: This elegantly handles multiple conditions. Each WHEN clause checks a condition, and if true, assigns the corresponding cod_user value.
  • Multiple conditions: The CASE statement efficiently manages the different user roles.
  • date update: The date field is updated to '12082014' for all matching rows. Remember to adjust the date format ('YYYYMMDD' in this example) to match your database settings.
  • WHERE clause: This filters the update to only affect rows where user_rol is 'student', 'assistant', or 'admin' and cod_office is '17389551'.

This method provides a more efficient and maintainable solution compared to using multiple individual UPDATE statements or complex nested IF structures. The CASE statement enhances readability and simplifies the overall query logic.

The above is the detailed content of How Can I Update Multiple Rows with Different Values in a Single MySQL 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