在MySQL中为NULL或空值设置自定义值

让我们首先创建一个表-

mysql> create table DemoTable
(
   Value varchar(100)
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values('100');
mysql> insert into DemoTable values('');
mysql> insert into DemoTable values('200');
mysql> insert into DemoTable values(null);

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

这将产生以下输出-

+-------+
| Value |
+-------+
| 100   |
|       |
| 200   |
| NULL  |
+-------+
4 rows in set (0.00 sec)

以下是为NULL或空值设置自定义值的查询-

mysql> select if(Value IS NULL or Value='','Garbage Value',Value) AS Result from DemoTable;

这将产生以下输出-

+---------------+
| Result        |
+---------------+
| 100           |
| Garbage Value |
| 200           |
| Garbage Value |
+---------------+
4 rows in set (0.00 sec)
猜你喜欢