当MySQL中此类列值之一为null时,连接两列
为避免在运行查询时出现任何问题,请使用IFNULL()
。让我们首先创建一个表-
mysql> create table DemoTable1793 ( StudentFirstName varchar(20), StudentLastName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1793 values('John','Smith'); mysql> insert into DemoTable1793 values('Carol',NULL); mysql> insert into DemoTable1793 values(NULL,'Brown');
使用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)