在 MySQL 中以 null 替換 0?


你可以使用 MySQL 中的 NULLIF() 用 null 替換 0。語法如下 -

SELECT *,NULLIF(yourColumnName,0) as anyVariableName from yourTableName;

為了理解上述語法,讓我們建立一個表。建立表的查詢如下 -

mysql> create table Replace0WithNULLDemo
   -> (
   -> Id int NOT NULL auto_increment,
   -> Name varchar(20),
   -> Marks int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.53 sec)

現在你可以使用插入命令在表中插入一些記錄。查詢如下 -

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('John',76);
Query OK, 1 row affected (0.16 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Carol',86);
Query OK, 1 row affected (0.20 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Sam',0);
Query OK, 1 row affected (0.17 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Mike',0);
Query OK, 1 row affected (0.16 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Larry',98);
Query OK, 1 row affected (0.19 sec)

mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Bob',0);
Query OK, 1 row affected (0.17 sec)

使用 select 語句從表中顯示記錄。查詢如下 -

mysql> select *from Replace0WithNULLDemo;

下面是輸出 -

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
|  1 | John  | 76    |
|  2 | Carol | 86    |
|  3 | Sam   | 0     |
|  4 | Mike  | 0     |
|  5 | Larry | 98    |
|  6 | Bob   | 0     |
+----+-------+-------+
6 rows in set (0.00 sec)

我們現在用 null 替換 0。查詢如下 -

mysql> select *,NULLIF(Marks,0) as ReplaceZeroWithNULL from Replace0WithNULLDemo;

以下是顯示新一列的輸出,其中 new 用 null 替換了 0 -

+----+-------+-------+---------------------+
| Id | Name  | Marks | ReplaceZeroWithNULL |
+----+-------+-------+---------------------+
| 1  | John  | 76    | 76                  |
| 2  | Carol | 86    | 86                  |
| 3  | Sam   | 0     | NULL                |
| 4  | Mike  | 0     | NULL                |
| 5  | Larry | 98    | 98                  |
| 6  | Bob   | 0     | NULL                |
+----+-------+-------+---------------------+
6 rows in set (0.00 sec)

更新於:2020 年 6 月 30 日

2K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.