mysql:根据另一列的值将列设置为上一行的值

时间:2017-10-04 01:07:20

标签: mysql variable-assignment user-variables

尝试执行以下操作:如果当前行的列c1等于前一行的c1,则将列c3设置为前一行的列c2;否则,将c3设置为NULL(或者只是不将其设置为任何内容)。有人能告诉我为什么以下查询导致c3为每一行都为空?

虚拟列就是能够设置变量@ c1和@ c2,它们应该存储该行的c1和c2值以用于下一行。顺便说一句,我错误地认为c3会先被更新,即它会得到之前的@ c2值(在@ c2被分配给当前的c2之前)?

UPDATE t SET c3 = IF (c1 = @c1, @c2, NULL), dummy1 = @c1:=c1, dummy2 = @c2:=c2;

1 个答案:

答案 0 :(得分:2)

我试过这个似乎工作正常。但如果您需要按特定顺序评估行,则需要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,因为这些是无操作。