"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 to Update NULL Values in a Table with Data from Rows Sharing the Same Name?

How to Update NULL Values in a Table with Data from Rows Sharing the Same Name?

Published on 2024-11-18
Browse:500

How to Update NULL Values in a Table with Data from Rows Sharing the Same Name?

Updating Rows with Data from Same-Table Siblings

Envision a table with a structure resembling this:

IDNAMEVALUE
1TestVALUE1
2Test2VALUE2
1Test2NULL
4TestNULL
1Test3VALUE3

Your task is to populate the NULL "VALUE" cells with data from other rows bearing the same "NAME" (i.e., "Test" and "Test2" should inherit values from their predecessors). The desired outcome is:

IDNAMEVALUE
1TestVALUE1
2Test2VALUE2
1Test2VALUE2
4TestVALUE1
1Test3VALUE3

The challenge lies in referencing rows within the same table that share a specific "NAME" value. The solution involves using a JOIN statement:

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

In this statement, the subquery (T1) extracts distinct rows with non-NULL and non-empty "VALUE" values. The main query (t) then joins with this subquery on the "ID" and "NAME" fields to identify the rows to be updated. As a result, the empty "VALUE" cells are populated with the corresponding values from the non-empty rows with the same "NAME" value.

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