有很多选项可以使用select语句替换NULL值。您可以使用CASE语句IFNULL()
或COALESCE()
情况1-使用IFNULL()
的语法IFNULL()
如下-
SELECT IFNULL(yourColumnName,’yourValue’) AS anyVariableName from yourTableName;
情况2-使用COALESCE()
的语法COALESCE()
如下-
SELECT COALESCE(yourColumnName,’yourValue’) AS anyVariableName from yourTableName;
情况3-使用CASE语句
CASE语句的语法。
SELECT CASE WHEN yourColumnName IS NULL THEN ‘yourValue’ ELSE yourColumnName END AS anyVariableName FROM yourTableName
要了解我们上面讨论的内容,让我们创建一个表。创建表的查询如下-
mysql> create table ReplaceNULLDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(10), -> Marks int, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into ReplaceNULLDemo(Name,Marks) values('Larry',90); mysql> insert into ReplaceNULLDemo(Name,Marks) values('Carol',NULL); mysql> insert into ReplaceNULLDemo(Name,Marks) values('David',NULL); mysql> insert into ReplaceNULLDemo(Name,Marks) values('Bob',67); mysql> insert into ReplaceNULLDemo(Name,Marks) values('Sam',78); mysql> insert into ReplaceNULLDemo(Name,Marks) values('Mike',NULL); mysql> insert into ReplaceNULLDemo(Name,Marks) values('John',98);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from ReplaceNULLDemo;
以下是输出-
+----+-------+-------+ | Id | Name | Marks | +----+-------+-------+ | 1 | Larry | 90 | | 2 | Carol | NULL | | 3 | David | NULL | | 4 | Bob | 67 | | 5 | Sam | 78 | | 6 | Mike | NULL | | 7 | John | 98 | +----+-------+-------+ 7 rows in set (0.00 sec)
现在让我们将NULL值转换为0。
情况1-使用IFNULL()
查询如下-
mysql> select ifnull(Marks,0) as ReplacementOfNULLWith0 from ReplaceNULLDemo;
以下是显示用NULL代替0的输出-
+------------------------+ | ReplacementOfNULLWith0 | +------------------------+ | 90 | | 0 | | 0 | | 67 | | 78 | | 0 | | 98 | +------------------------+ 7 rows in set (0.00 sec)
情况2-使用COALESCE()
查询如下-
mysql> select coalesce(Marks,0) as ReplacementOfNULLWith0 from ReplaceNULLDemo;
以下是显示用NULL代替0的输出-
+------------------------+ | ReplacementOfNULLWith0 | +------------------------+ | 90 | | 0 | | 0 | | 67 | | 78 | | 0 | | 98 | +------------------------+ 7 rows in set (0.00 sec)
情况3-使用CASE语句。
查询如下-
mysql> select case -> when Marks is null then 0 -> else Marks end as ReplacementOfNULLWith0 -> from ReplaceNULLDemo;
以下是显示用NULL代替0的输出-
+------------------------+ | ReplacementOfNULLWith0 | +------------------------+ | 90 | | 0 | | 0 | | 67 | | 78 | | 0 | | 98 | +------------------------+ 7 rows in set (0.00 sec)