选择一个字段,如果为空,则使用 MySQL 选择另一个字段?

mysqlmysqli database

为此,请使用 COALESCE()。让我们首先创建一个表 −

mysql> create table DemoTable1470
   -> (
   -> FirstName varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.57 sec)

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

mysql> insert into DemoTable1470 values('Robert',23);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1470 values('Bob',NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1470 values(NULL,25);
Query OK, 1 row affected (0.15 sec)

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

mysql> select * from DemoTable1470;

这将产生以下输出 −

+-----------+------+
| FirstName | Age  |
+-----------+------+
| Robert    |   23 |
| Bob       | NULL |
| NULL      |   25 |
+-----------+------+
3 rows in set (0.00 sec)

以下是选择一个字段的查询,如果它为空,则选择另一个 −

mysql> select coalesce(FirstName,Age) as FirstNameOrAgeValue from DemoTable1470;

这将产生以下输出 −

+---------------------+
| FirstNameOrAgeValue |
+---------------------+
| Robert              |
| Bob                 |
| 25                  |
+---------------------+
3 rows in set (0.00 sec)

相关文章