为此,您可以使用COALESCE()
。让我们首先创建一个表-
mysql> create table DemoTable1336 -> ( -> FirstName varchar(20) -> , -> SecondName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1336 values('John',NULL); mysql> insert into DemoTable1336 values(NULL,'Chris'); mysql> insert into DemoTable1336 values('David','Mike');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1336;
这将产生以下输出-
+-----------+------------+ | FirstName | SecondName | +-----------+------------+ | John | NULL | | NULL | Chris | | David | Mike | +-----------+------------+ 3 rows in set (0.00 sec)
以下是即使字段设置为null的查询,也可以在MySQL中选择其他字段-
mysql> select coalesce(FirstName,SecondName) as AlternateName from DemoTable1336;
这将产生以下输出-
+---------------+ | AlternateName | +---------------+ | John | | Chris | | David | +---------------+ 3 rows in set (0.00 sec)