简体   繁体   English

MySQL:如果上一行与当前行相同则更新当前值

[英]Mysql: update current value if previous row are same with current row

How do i update current row value if my previous row are same with current row. 如果上一行与当前行相同,如何更新当前行值。

example: 例: 在此处输入图片说明

the curent row is 68, previous row is also 68.. i would i like to update current row become 68-20 which is 48. 当前行是68,上一行也是68 ..我想将当前行更新为68-20,即48。

same for 98-20 = 78. 对于98-20 = 78则相同。

so that the corrected data will look like: 这样校正后的数据将如下所示: 在此处输入图片说明

i have more than 1000 record like this, which cant update the record one by one manually. 我有1000多个这样的记录,无法手动一次更新记录。

update table1 set DIH_QTY_BALANCE=DIH_QTY_BALANCE-DIH_REORDER_QTY

WHERE how to put the previous row same as current on where clause? 在where子句中,如何将上一行与当前行相同?

Here is the Schema + data: http://pastebin.com/T1tYDT6Y 这是Schema +数据: http : //pastebin.com/T1tYDT6Y

too large for sqlfiddle. 对于sqlfiddle太大。

any help would be great. 任何帮助都会很棒。

As far as I remember, MySQL has problems to select from the same table in an update statement. 据我所知,MySQL在更新语句中无法从同一表中进行选择。 And this is what you would have to do, because in order to update a record or not, you'd have to select its previous record from the same table. 这就是您要做的,因为要更新记录或不更新记录,您必须从同一表中选择其先前的记录。

So create a temporary table, give it row numbers, then select from it with a self join, to compare each record with its previous record. 因此,创建一个临时表,为其指定行号,然后通过自连接从中选择表,以将每个记录与其先前的记录进行比较。

create temporary table temp
(
  rownum int, 
  dihistoryid int, 
  dih_qty_balance int
) engine = memory;

set @num = 0;

insert into temp
  select 
    @num := @num + 1 as rownum, 
    dihistoryid, 
    dih_qty_balance 
  from mytable
  order by dihistoryid;

update mytable
set dih_qty_balance = dih_qty_balance - dih_reorder_qty
where dihistoryid in
(
  select current.dihistoryid
  from temp current
  join temp previous on previous.rownum = current.rownum - 1
  where previous.dih_qty_balance = current.dih_qty_balance
);

drop temporary table temp;

May be something like this 可能是这样的

SELECT DIH_QTY_BALANCE,
       (SELECT DIH_QTY_BALANCE FROM example e2
        WHERE e2.DIHISTORYID < e1.DIHISTORYID
        ORDER BY DIHISTORYID DESC LIMIT 1) as previous_value,
       (SELECT value FROM example e3
        WHERE e3.DIHISTORYID > e1.DIHISTORYID 
        ORDER BY DIHISTORYID ASC LIMIT 1) as next_value
FROM example e1

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

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