Home > Database > Mysql Tutorial > body text

How to Update Multiple Records in SQL Based on a Single Record Change?

Susan Sarandon
Release: 2024-11-06 17:34:02
Original
124 people have browsed it

How to Update Multiple Records in SQL Based on a Single Record Change?

Modifying Multiple Records Based on Single Record Change in SQL

Question:

How to update the positions of multiple records in a table based on the change of a single record's position?

Solution:

To address this issue, a complex query that modifies several records might be required. However, with a simple adjustment to the data structure, we can simplify the process and accomplish it with a single query that modifies only the desired record.

In the provided example, the table contains a "Position" field to order items within a list identified by "ListID." Moving an item (e.g., "Pears" to before "Chips") involves setting its position to the desired position and adjusting the positions of all items in between.

Our goal is to achieve a single query without relying on additional processing or multiple queries.

Subsequently, we can use the following query:

<code class="sql">UPDATE my_table SET position = 15 WHERE listId=1 AND name = 'Pears';</code>
Copy after login

Suppose, in the future, gaps appear between items due to repeated reordering. To resolve this issue, we can periodically execute the following query:

<code class="sql">UPDATE my_table SET position = position * 10;</code>
Copy after login

By multiplying the position values by 10, we introduce sufficient gaps to accommodate future adjustments without losing the ordering information.

The above is the detailed content of How to Update Multiple Records in SQL Based on a Single Record Change?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!