[英]How to update a MySQL row based on previous row?
I have a table like this: 我有一张这样的桌子:
ACTUAL TABLE 实际表
ID | Type | Number
----------+----------
1 | x | 2000
2 | y | 4500
3 | y | 4500
4 | x | 3000
5 | y | 5000
6 | x | 4000
7 | y | 7500
8 | y | 7500
And I want to update the y
to be exact as the x
before it: 我想将
y
精确地更新为x
之前的x
:
EXPECTED TABLE 预期表
ID | Type | Number
----------+----------
1 | x | 2000
2 | y | 2000
3 | y | 2000
4 | x | 3000
5 | y | 3000
6 | x | 4000
7 | y | 4000
8 | y | 4000
How should I do that in MySQL? 我应该如何在MySQL中做到这一点?
Try Like This 像这样尝试
t
is tablename t
是表名
a
is type a
是类型
va
is number va
是数字
update t join (
select curr.id, max(prior.id) prior_id
from t curr
join t prior
on prior.a = 'x'
and prior.id < curr.id
where curr.a = 'y'
group by curr.id) g
on g.id = t.id
join t v on v.id = g.prior_id
set t.va = v.va;
只需根据您的ID进行更新: UPDATE <tablename> SET <fieldname> = (SELECT <fieldname> FROM <tablename> WHERE id = 1) WHERE id = 2
这可能有用。
START TRANSACTION;
SELECT id, va into @max_id, @value_x FROM t
WHERE a = 'x'
ORDER BY id DESC
LIMIT 1;
UPDATE t
set va = @value_x
where ID > @max_id;
COMMIT;
Try to get the value of x and id from the table first, into sql variables. 尝试首先从表中获取x和id的值,并将其放入sql变量中。 Then do a simple update using those variabes.
然后使用这些变量进行简单的更新。
UPDATE my_table a
JOIN
(
SELECT y.*
, MAX(x.number) max_number
FROM my_table y
JOIN my_table x
ON x.type = 'x'
AND x.id <= y.id
GROUP
BY y.id
) b
ON b.id = a.id
SET a.number = b.max_number;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.