我有一张这样的表:
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
我希望将y
更新为与之前的x
完全相同:
预期表
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
我应该如何在MySQL中做到这一点?
答案 0 :(得分:1)
尝试这样
t
是tablename
a
是
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;
答案 1 :(得分:0)
根据您的ID更新:
UPDATE <tablename> SET <fieldname> = (SELECT <fieldname> FROM <tablename> WHERE id = 1) WHERE id = 2
它可能会奏效。
答案 2 :(得分:0)
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;
尝试首先从表中获取x和id的值,转换为sql变量。 然后使用这些变量进行简单更新。
答案 3 :(得分:0)
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;