在 MySQL 中更新現有列資料並移除帶有字串和數字的 varchar 列中的最後一個字串


首先,我們建立一個表 −

mysql> create table DemoTable
(
   Download varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values('120 Gigabytes');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('190 Gigabytes');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('250 Gigabytes');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('1000 Gigabytes');
Query OK, 1 row affected (0.12 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+----------------+
| Download       |
+----------------+
| 120 Gigabytes  |
| 190 Gigabytes  |
| 250 Gigabytes  |
| 1000 Gigabytes |
+----------------+
4 rows in set (0.00 sec)

以下是更新現有列資料並移除最後一個字串的查詢 −

mysql> update DemoTable set Download=LEFT(Download, INSTR(Download, ' ') - 1);
Query OK, 4 rows affected (0.16 sec)
Rows matched: 4 Changed: 4 Warnings: 0

讓我們再次檢查表記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+----------+
| Download |
+----------+
| 120      |
| 190      |
| 250      |
| 1000     |
+----------+
4 rows in set (0.00 sec)

更新於: 2019 年 9 月 25 日

224 次瀏覽

開啟您的 職業

完成課程獲取認證

開始
廣告
© . All rights reserved.