"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do I update empty values in a table based on data from other rows with the same name?

How do I update empty values in a table based on data from other rows with the same name?

Published on 2024-11-16
Browse:129

How do I update empty values in a table based on data from other rows with the same name?

Copying Data Between Rows in a Table

In database management, it is often necessary to update rows based on data from other rows within the same table. Consider a table with columns ID, NAME, and VALUE that contains duplicate NAME values, as follows:

ID   |   NAME    |  VALUE  |
----------------------------
 1   |   Test    |  VALUE1 |
 2   |   Test2   |  VALUE2 |
 1   |   Test2   |         |
 4   |   Test    |         |
 1   |   Test3   |  VALUE3 |

Suppose we want to update the empty VALUE fields in rows with duplicate NAME values. To achieve this, we can employ SQL queries that reference and update values within the same table.

One approach involves using an UPDATE statement with a join. In the following query, we join the data_table twice, aliasing them as dt1 and dt2:

UPDATE data_table dt1, data_table dt2 
SET dt1.VALUE = dt2.VALUE 
WHERE dt1.NAME = dt2.NAME AND dt1.VALUE = '' AND dt2.VALUE != '' 

This query identifies and updates the empty VALUE fields (where dt1.VALUE is empty) with non-empty VALUEs from other rows with the same NAME (where dt2.VALUE is not empty).

As an alternative, we can use a subquery to identify the rows with non-empty VALUEs and join it back to the original table for updating:

UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
                        FROM data_table
                       WHERE VALUE IS NOT NULL AND VALUE != '') t1
   SET t.VALUE = t1.VALUE
 WHERE t.ID = t1.ID
   AND t.NAME = t1.NAME

Both of these queries will result in the desired output:

ID   |   NAME    |  VALUE  |
----------------------------
 1   |   Test    |  VALUE1 |
 2   |   Test2   |  VALUE2 |
 1   |   Test2   |  VALUE2 |
 4   |   Test    |  VALUE1 |
 1   |   Test3   |  VALUE3 |

These approaches provide flexibility in manipulating data within a table, allowing you to update values based on criteria that include other rows in the same table.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3