如何从MySQL中的另一个字段派生一个字段的值?

为此,可以使用用户定义变量的概念。让我们首先创建一个表-

create table DemoTable1868
     (
     Value int
     );

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

insert into DemoTable1868 values(10);
insert into DemoTable1868 values(20);
insert into DemoTable1868 values(30);
insert into DemoTable1868 values(40);

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

select * from DemoTable1868;

这将产生以下输出-

+-------+
| Value |
+-------+
|    10 |
|    20 |
|    30 |
|    40 |
+-------+
4 rows in set (0.00 sec)

这是从MySQL的另一个字段派生一个字段的值的查询-

select  Value,(@iterator:=Value+@iterator) as SecondColumn from DemoTable1868,( select @iterator:=0) tbl;

这将产生以下输出-

+-------+--------------+
| Value | SecondColumn |
+-------+--------------+
|    10 |           10 |
|    20 |           30 |
|    30 |           60 |
|    40 |          100 |
+-------+--------------+
4 rows in set (0.00 sec)