僅為 MySQL 表中的 NULL 值設定值


使用 IFNULL 檢查 NULL 值,並使用 SET 命令設定值。讓我們首先建立一個表 -

mysql> create table DemoTable817(Value int);
Query OK, 0 rows affected (0.53 sec)

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

mysql> insert into DemoTable817 values(10);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable817 values(null);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable817 values(20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable817 values(null);
Query OK, 1 row affected (0.11 sec)

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

mysql> select *from DemoTable817;

這將產生以下輸出 -

+-------+
| Value |
+-------+
| 10    |
| NULL  |
| 20    |
| NULL  |
+-------+
4 rows in set (0.00 sec)

以下是僅為 NULL 值設定值所用的查詢 -

mysql> update DemoTable817 set Value=IFNULL(Value,0);
Query OK, 2 rows affected (0.17 sec)
Rows matched: 4 Changed: 2 Warnings: 0

讓我們再次檢查表記錄 -

mysql> select *from DemoTable817;

這將產生以下輸出 -

+-------+
| Value |
+-------+
| 10    |
| 0     |
| 20    |
| 0     |
+-------+
4 rows in set (0.00 sec)

更新於: 03-Sep-2019

130 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.