如何在 MySQL 中使用特定值更新某個欄位,前提是該欄位為 null?


要更新為 null 的欄位,請使用 UPDATE 命令和 IS NULL 屬性。我們首先建立一個表 -

mysql> create table DemoTable
(
   StudentScore int
);
Query OK, 0 rows affected (0.47 sec)

使用 insert 命令向表中插入一些記錄 -

mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

這將產生以下輸出 -

+--------------+
| StudentScore |
+--------------+
|           89 |
|         NULL |
|           45 |
|         NULL |
|           56 |
+--------------+
5 rows in set (0.00 sec)

以下是 MySQL 中更新為 null 的欄位的查詢 -

mysql> update DemoTable set StudentScore=30 where StudentScore IS NULL;
Query OK, 2 rows affected (0.34 sec)
Rows matched: 2 Changed: 2 Warnings: 0

讓我們再次檢查一下表記錄。

mysql> select *from DemoTable;

這將產生以下輸出 -

+--------------+
| StudentScore |
+--------------+
|           89 |
|           30 |
|           45 |
|           30 |
|           56 |
+--------------+
5 rows in set (0.00 sec)

更新於:2019-09-24

1 千+瀏覽量

開啟您的事業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.