MySQL 查询在获取数据时将多个列中的空值替换为空字符串
mysqlmysqli database
为此,您可以使用 IFNULL() 或 COALESCE()。让我们首先创建一个表 −
mysql> create table DemoTable1849 ( ClientFirstName varchar(20), ClientLastName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1849 values('John',NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1849 values(NULL,'Miller'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1849 values(NULL,NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1849 values('Chris','Brown'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1849;
这将产生以下输出 −
+-----------------+----------------+ | ClientFirstName | ClientLastName | +-----------------+----------------+ | John | NULL | | NULL | Miller | | NULL | NULL | | Chris | Brown | +-----------------+----------------+ 4 rows in set (0.00 sec)
这是在获取数据时将几列中的空值替换为空字符串的查询 −
mysql> select ifnull(ClientFirstName,'') as ClientFirstName,ifnull(ClientLastName,'') as ClientLastName from DemoTable1849;
这将产生以下输出 −
+-----------------+----------------+ | ClientFirstName | ClientLastName | +-----------------+----------------+ | John | | | | Miller | | | | | Chris | Brown | +-----------------+----------------+ 4 rows in set (0.00 sec)