在更新 MySQL 表格时执行运算(加、减、乘、除)?
以下是执行加法 (+) 运算符的语法 −
update yourTableName set yourColumnName3=(yourColumnName1+yourColumnName2)
以上语法仅适用于加法运算符。你需根据其他运算符更改符号,如 -、*、/。我们先来创建一个表格 −
mysql> create table DemoTable -> ( -> Number1 int, -> Number2 int, -> AddResult int, -> MinusResult int, -> MultiplyResult int, -> DivideResult int -> ); Query OK, 0 rows affected (0.89 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into DemoTable(Number1,Number2) values(40,20); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表格中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+---------+---------+-----------+-------------+----------------+--------------+ | Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult | +---------+---------+-----------+-------------+----------------+--------------+ | 40 | 20 | NULL | NULL | NULL | NULL | +---------+---------+-----------+-------------+----------------+--------------+ 1 row in set (0.00 sec)
以下是使用 MySQL 中的 UPDATE 执行加法、减法、乘法和除法等运算的查询 −
mysql> update DemoTable set AddResult=(Number1+Number2); Query OK, 1 row affected (0.22 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> update DemoTable set MinusResult=(Number1-Number2); Query OK, 1 row affected (0.08 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> update DemoTable set MultiplyResult=(Number1*Number2); Query OK, 1 row affected (0.08 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> update DemoTable set DivideResult=(Number1/Number2); Query OK, 1 row affected (0.07 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次查看表记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+---------+---------+-----------+-------------+----------------+--------------+ | Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult | +---------+---------+-----------+-------------+----------------+--------------+ | 40 | 20 | 60 | 20 | 800 | 2 | +---------+---------+-----------+-------------+----------------+--------------+ 1 row in set (0.00 sec)
广告