Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

mysql - Update row with data from another row in the same table

I've got a table which looks something like this

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

I'm looking for a way to update the values 'Test2' and 'Test' with the data from other rows in the 'VALUE' column with the same 'NAME' (The ID is not unique here, a composite key of the ID and NAME make a row unique). For example, the output I'm looking for is:

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

If it was in another table I'd be fine, but I'm at a loss as to how I can reference a different row within the current table with the same NAME value.

Update

After modifying manji query, below is the query I used for a working solution. Thanks all!

UPDATE data_table dt1, data_table dt2 
SET dt1.VALUE = dt2.VALUE 
WHERE dt1.NAME = dt2.NAME AND dt1.VALUE = '' AND dt2.VALUE != '' 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...