其中一个列值为 MySQL 中的空值时,连接两列


若要避免在运行查询时出现问题,请使用 IFNULL()。我们首先创建一个表 -

mysql> create table DemoTable1793
     (
     StudentFirstName varchar(20),
     StudentLastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1793 values('John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1793 values('Carol',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1793 values(NULL,'Brown');
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1793;

这将产生以下输出 -

+------------------+-----------------+
| StudentFirstName | StudentLastName |
+------------------+-----------------+
| John             |           Smith |
| Carol            |            NULL |
| NULL             |           Brown |
+------------------+-----------------+
3 rows in set (0.00 sec)

以下是其中一个列值为 null 时连接两列的查询 -

mysql> select concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) from DemoTable1793;

这将产生以下输出 -

+----------------------------------------------------------------+
| concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) |
+----------------------------------------------------------------+
| JohnSmith                                                      |
| Carol                                                          |
| Brown                                                          |
+----------------------------------------------------------------+
3 rows in set (0.00 sec)

更新于:2019 年 12 月 23 日

1000+ 浏览量

开启你的 职业

完成课程后获得认证

开始
广告
© . All rights reserved.