在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)
当其中一个列的值为空时,以下是连接两个列的查询−
mysql> select concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) from DemoTable1793;
这将产生以下输出−
+----------------------------------------------------------------+
| concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) |
+----------------------------------------------------------------+
| JohnSmith |
| Carol |
| Brown |
+----------------------------------------------------------------+
3 rows in set (0.00 sec)
阅读更多:MySQL 教程