简体   繁体   中英

MySQL: How to update fields with the values of the record before this one

I have a large table with 1 mln records. I get this table from another company. All records have an autonumber id as PRIMARY KEY. A lot of the fields are empty, because some records "belong together" (as a group) and these fields are only filled in for the first record (sort of header record).

I want to fill in the same values in all following records until that field is not empty (that is where a new "header" from a new group of records starts). (I know, bad database design, but it is what I get and I want to turn it into better database design as soon as it gets in, and this is just the first necessary step into a longer step process to get there.)

I am having a hard time getting this right. I want to UPDATE the table, in order of id, where, if the specific fields are empty, they are filled in with the values of the previous record.

I tried different solutions, all of them turn out not to be working.

My last one:

UPDATE t1
SET f1 =
        (SELECT t2.f1 FROM t1 AS t2  
                WHERE t2.id = t1.id-1) , 
    Verzend_tijd=
        (SELECT t3.f2 FROM t1 as t3 
                WHERE t3.id = t1.id-1)  
WHERE  t2.f1 = '' 
ORDER BY t1.id

I get the error:

You can't specify target table 't1' for update in FROM clause

Anyone an idea how to get this done? I also tried with an INNER JOIN but it turns our I cannot do an ORDER BY in UPDATE+INNER JOIN, and the order is important!

I am a bit at a loss and Googling didn't bring me anything either.

After more and more Googling I found the answer right here on this website:

Mysql Updating a record with a value from the previous record

Sorry for the inconvenience

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM