简体   繁体   English

如何用 MySQL 中以前的非零值替换零值?

[英]how to replace the zero values with the previous non-zero value in MySQL?

Disclaimer: This is not a duplicate question.免责声明:这不是一个重复的问题。 I have research before posting发帖前我有研究

在此处输入图片说明

The value in red circle should have "2" value, because the previous non-zero value is number 2. how to do that in mysql update query ?红色圆圈中的值应该有“2”值,因为之前的非零值是数字 2。如何在 mysql 更新查询中做到这一点? as you can see there are other rows that has the same zero value that needs to be having the previous non-zero value.如您所见,还有其他行具有相同的零值,需要具有先前的非零值。

You could use an inline query:您可以使用内联查询:

select 
    pk,
    case when val1 = 0 
        then (select val1 from mytable t1 where t1.pk < t.pk and t1.val1 != 0 order by pk desc limit 1)
        else val1
    end val1,
    val2,
    val3,
    received_date
from mytable t

If you only want to select the correct values use如果您只想选择正确的值,请使用

  select pk, val1, @previous as previous_v, @previous := val1
  from your_table
  cross join (select @previous := 0) p
  order by pk

If you also want to update the table use如果您还想更新表使用

update your_table t
join
(
  select pk, val1, @previous as previous_v, @previous := val1
  from your_table
  cross join (select @previous := 0) p
  order by pk
) tmp on tmp.pk = t.pk
set t.val1 = previous_v
where t.val1 = 0

SQLFiddle demo SQLFiddle 演示

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

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