您可以使用CONCAT()
方法来连接值,而使用方法IFNULL()
来处理NULL值。语法如下:
SELECT CONCAT('anyStringValue:',IFNULL(yourColumnName, 'anyStringValue’)) AS anyVariableName FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table ConcatValues -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstName varchar(20), -> MiddleName varchar(20), -> LastName varchar(20), -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into ConcatValues(FirstName,MiddleName,LastName) values('John' ,NULL ,'Smith'); mysql> insert into ConcatValues(FirstName,MiddleName,LastName) values('Carol' ,NULL ,'Taylor'); mysql> insert into ConcatValues(FirstName,MiddleName,LastName) values('David' ,NULL ,'Miller');
使用select语句显示表中的所有记录。查询如下:
mysql> select *from ConcatValues;
以下是输出:
+----+-----------+------------+----------+ | Id | FirstName | MiddleName | LastName | +----+-----------+------------+----------+ | 1 | Mary | Elizabeth | Smith | | 2 | John | NULL | Smith | | 3 | Carol | NULL | Taylor | | 4 | David | NULL | Miller | +----+-----------+------------+----------+ 4 rows in set (0.00 sec)
这是处理NULL和连接值的查询:
mysql> select -> concat('The middle name is:',IFNULL(MiddleName, 'Not Available')) AS MiddleName -> from ConcatValues;
以下是输出:
+----------------------------------+ | MiddleName | +----------------------------------+ | The middle name is:Elizabeth | | The middle name is:Not Available | | The middle name is:Not Available | | The middle name is:Not Available | +----------------------------------+ 4 rows in set (0.00 sec)