如何在 MySQL 中向每行添加内容?


可以使用 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)

更新于: 30-07-2019

409 次浏览

开启你的职业生涯

完成课程以获得认证

开始
广告