UPDATE 在 MySQL 中更新列以追加資料?


為了實現這一目標,語法如下。

UPDATE yourTableName set
yourColumnName=concat(ifnull(yourColumnName,””),’anyValue1,anyValue2,anyValue);

為了理解上面的語法,我們首先建立一個表。建立表的查詢如下 -

mysql> create table AppendDataDemo
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentAge int
-> );
Query OK, 0 rows affected (1.54 sec)

使用 insert 命令在表中插入一些記錄。查詢如下。

mysql> insert into AppendDataDemo values(101,'John',23);
Query OK, 1 row affected (0.24 sec)

mysql> insert into AppendDataDemo values(102,null,24);
Query OK, 1 row affected (0.74 sec)

mysql> insert into AppendDataDemo values(103,'Mike',26);
Query OK, 1 row affected (0.12 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下。

mysql> select *from AppendDataDemo;

以下是輸出。

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 101       | John        | 23         |
| 102       | NULL        | 24         |
| 103       | Mike        | 26         |
+-----------+-------------+------------+
3 rows in set (0.00 sec)

以下是更新 StudentName 列並將其資料追加到“Carol, Sam, Maria”的查詢。

mysql> update AppendDataDemo set StudentName=concat(ifnull(StudentName,""), ' Carol,Sam,Maria');
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0

使用 select 語句從表中檢查表記錄。查詢如下。

mysql> select *from AppendDataDemo;

以下是顯示追加資料的輸出。

+-----------+----------------------+------------+
| StudentId | StudentName          | StudentAge |
+-----------+----------------------+------------+
| 101       | John Carol,Sam,Maria | 23         |
| 102       | Carol,Sam,Maria      | 24         |
| 103       | Mike Carol,Sam,Maria | 26         |
+-----------+----------------------+------------+
3 rows in set (0.03 sec)

已更新:2020 年 6 月 29 日

2K+ 次瀏覽

開啟您的 職業

完成課程後獲得認證

開始吧
廣告
© . All rights reserved.