MySQL 查詢透過數字增量值(例如 John1、John2、John3 等)更新列中的所有值。


要將列中的所有值更新為 John1、John2 等,你需要設定增量值 1、2、3 等,並將它們串聯到記錄中。讓我們首先建立一個表 -

mysql> create table DemoTable
(
   StudentId varchar(80)
);
Query OK, 0 rows affected (0.50 sec)

使用 insert 命令在表中插入一些記錄。這裡,對於我們的示例,我們設定了類似的名稱 -

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)

使用 select 語句顯示來自該表中的所有記錄 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+-----------+
| StudentId |
+-----------+
|      John |
|      John |
|      John |
|      John |
|      John |
+-----------+
5 rows in set (0.00 sec)

以下是要使用數字增量值更新/串聯所有名稱的查詢 -

mysql> update DemoTable,(select @row := 0) r set StudentId =concat('John',@row := @row+ 1);
Query OK, 5 rows affected (0.11 sec)
Rows matched: 5 Changed: 5 Warnings: 0

讓我們再次檢查表記錄 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+-----------+
| StudentId |
+-----------+
|     John1 |
|     John2 |
|     John3 |
|     John4 |
|     John5 |
+-----------+
5 rows in set (0.00 sec)

更新於: 2019-10-04

204 次瀏覽

開始你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.