在 MySQL 中更新空白單元格為 NULL,會將 MySQL 中的所有單元格都變為 NULL 嗎?


僅更新空白單元格為 NULL,在 MySQL 中使用 NULLIF()。我們首先建立一個表 -

mysql> create table DemoTable
(
   Name varchar(50)
);
Query OK, 0 rows affected (1.73 sec)

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

mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values('');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

這將生成以下輸出 -

+-------+
| Name  |
+-------+
| Mike  |
|       |
| David |
|       |
| Mike  |
+-------+
5 rows in set (0.00 sec)

以下是僅將空白單元格更新為 NULL 的查詢 -

mysql> update DemoTable
   set Name=NULLIF(Name,'');
Query OK, 2 rows affected (0.19 sec)
Rows matched: 5 Changed: 2 Warnings: 0

讓我們再次檢查表記錄 -

mysql> select *from DemoTable;

這將生成以下輸出 -

+-------+
| Name  |
+-------+
| Mike  |
| NULL  |
| David |
| NULL  |
| Mike  |
+-------+
5 rows in set (0.00 sec)

更新於:03-10-2019

83 次瀏覽

開啟你的 職業

完成該課程即可獲得證書

開始
廣告