假设这样的起始表:
mysql> SELECT * FROM test;
+------+------+
| col1 | col2 |
+------+------+
| a | 1 |
| b | 2 |
| c | 1 |
| d | 3 |
+------+------+
...你可以通过这样做得到你想要的结果:
mysql> SELECT col1, col2, @a := @a + col2 AS col3
-> FROM test JOIN (SELECT @a := 0) t
-> ORDER BY col1;
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| a | 1 | 1 |
| b | 2 | 3 |
| c | 1 | 4 |
| d | 3 | 7 |
+------+------+------+
4 rows in set (0.00 sec)
如果你颠倒顺序,你会根据你的问题陈述得到结果,即col2
加上col3
显示顺序中的前一个:
mysql> SELECT col1, col2, @a := @a + col2 AS col3
-> FROM test JOIN (SELECT @a := 0) t
-> ORDER BY col1 DESC;
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| d | 3 | 3 |
| c | 1 | 4 |
| b | 2 | 6 |
| a | 1 | 7 |
+------+------+------+
4 rows in set (0.00 sec)