我试过这个,它似乎工作正常。但是,ORDER BY
如果您需要按特定顺序评估行,则需要一个。
create table t (c1 int, c2 int, c3 int, id int auto_increment primary key);
insert into t (c1, c2, c3) values
(1, 2, 3),
(1, 4, 5),
(2, 6, 7);
select * from t;
+------+------+------+----+
| c1 | c2 | c3 | id |
+------+------+------+----+
| 1 | 2 | 3 | 1 |
| 1 | 4 | 5 | 2 |
| 2 | 6 | 7 | 3 |
+------+------+------+----+
update t set c3=if(c1=@c1,@c2,NULL), c1 = @c1:=c1, c2 = @c2:=c2 order by id;
Query OK, 3 rows affected (0.02 sec)
Rows matched: 3 Changed: 3 Warnings: 0
select * from t;
+------+------+------+----+
| c1 | c2 | c3 | id |
+------+------+------+----+
| 1 | 2 | NULL | 1 |
| 1 | 4 | 2 | 2 |
| 2 | 6 | NULL | 3 |
+------+------+------+----+
请注意,我不需要虚拟列。只需设置 c1=c1 和 c2=c2,因为它们是无操作的。