如何在MySQL中将零值替换为先前的非零值?

时间:2019-12-12 07:04:41

标签: mysql

免责声明:这不是重复的问题。发布之前我已经研究了

enter image description here

红色圆圈中的值应为“ 2”,因为先前的非零值是数字2。如何在mysql更新查询中做到这一点?如您所见,还有其他具有相同零值的行需要具有先前的非零值。

2 个答案:

答案 0 :(得分:2)

您可以使用内联查询:

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

答案 1 :(得分:1)

如果只想选择正确的值,请使用

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

如果您还想更新表,请使用

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