在 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)
广告