MySQL SELECT将列值与先前值相加

为此,您可以使用会话变量。让我们首先创建一个表-

mysql> create table DemoTable809(Price int);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable809 values(40);
mysql> insert into DemoTable809 values(50);
mysql> insert into DemoTable809 values(60);

使用select语句显示表中的所有记录-

mysql> select *from DemoTable809;

这将产生以下输出-

+-------+
| Price |
+-------+
|    40 |
|    50 |
|    60 |
+-------+
3 rows in set (0.00 sec)

以下是将列值与上一个值求和的查询-

mysql> select @currentSum:=@currentSum+Price from DemoTable809;

这将产生以下输出-

+--------------------------------+
| @currentSum:=@currentSum+Price |
+--------------------------------+
|                             40 |
|                             90 |
|                            150 |
+--------------------------------+
3 rows in set (0.00 sec)