简体   繁体   English

MySQL:如何使用此前的记录值更新字段

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

I have a large table with 1 mln records. 我有一张包含1百万条记录的大桌子。 I get this table from another company. 我从另一家公司得到这张桌子。 All records have an autonumber id as PRIMARY KEY. 所有记录的自动编号都是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. 我想按照id的顺序更新表,其中,如果特定字段为空,则使用前一记录的值填充它们。

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! 我也尝试过INNER JOIN,但它变成了我在UPDATE + INNER JOIN中不能做ORDER BY,顺序很重要!

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 Mysql使用上一条记录中的值更新记录

Sorry for the inconvenience 抱歉给你带来不便

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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