如何在 MySQL 中向每行添加值?
mysqlmysqli database
您可以使用 UPDATE 命令向 MySQL 中的每一行添加值。
让我们看看您的列何时为整数。语法如下:
UPDATE yourTableName SET yourIntegerColumnName = yourIntegerColumnName+anyValue; UPDATE yourTableName SET yourIntegerColumnName = anyValue WHERE yourIntegerColumnName IS NULL;
您可以为日期列名称添加值。语法如下:
UPDATE yourTableName SET yourDateColumnName = DATEADD(yourDateColumnName,INTERVAL anyIntegerMonth)
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table addEachRowValue -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Amount int, -> ShippingDate date, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.50 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下:
mysql> insert into addEachRowValue(Amount,ShippingDate) values(100,'2019-02-21'); Query OK, 1 row affected (0.15 sec) mysql> insert into addEachRowValue(Amount,ShippingDate) values(10,'2013-04-22'); Query OK, 1 row affected (0.19 sec) mysql> insert into addEachRowValue(Amount,ShippingDate) values(110,'2015-10-25'); Query OK, 1 row affected (0.15 sec) mysql> insert into addEachRowValue(Amount,ShippingDate) values(150,'2016-03-27'); Query OK, 1 row affected (0.29 sec) mysql> insert into addEachRowValue(Amount,ShippingDate) values(190,'2018-12-29'); Query OK, 1 row affected (0.20 sec)
使用 select 语句显示表中的所有记录。查询如下:
mysql> select *from addEachRowValue;
输出结果如下:
+----+--------+--------------+ | Id | Amount | ShippingDate | +----+--------+--------------+ | 1 | 100 | 2019-02-21 | | 2 | 10 | 2013-04-22 | | 3 | 110 | 2015-10-25 | | 4 | 150 | 2016-03-27 | | 5 | 190 | 2018-12-29 | +----+--------+--------------+ 5 rows in set (0.00 sec)
以下查询用于向 Amount 列中的每一行添加一个整数类型的值:
mysql> update addEachRowValue -> set Amount=Amount+20; Query OK, 5 rows affected (0.85 sec) Rows matched: 5 Changed: 5 Warnings: 0
现在您可以检查 Amount 列的所有更新值。查询如下:
mysql> select Amount from addEachRowValue;
输出结果如下:
+--------+ | Amount | +--------+ | 120 | | 30 | | 130 | | 170 | | 210 | +--------+ 5 rows in set (0.00 sec)
以下是为日期列添加值的查询:
mysql> update addEachRowValue -> set ShippingDate=adddate(ShippingDate,interval 1 month); Query OK, 5 rows affected (0.31 sec) Rows matched: 5 Changed: 5 Warnings: 0
现在您可以从表中检查日期列的所有更新值。查询如下:
mysql> select ShippingDate from addEachRowValue;
输出结果如下:
+--------------+ | ShippingDate | +--------------+ | 2019-03-21 | | 2013-05-22 | | 2015-11-25 | | 2016-04-27 | | 2019-01-29 | +--------------+ 5 rows in set (0.00 sec)