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 ? 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
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.