MySQL查询,用于组合单一列中的两列?
你可以为此使用COALESCE()函数。在COALESCE()函数中,它会返回该列中的第一个非NULL值。为了理解此概念,我们首先创建一个演示表
mysql> create table combineTwoColumnsDemo -> ( -> UserId int, -> UserName varchar(20), -> UserAge int -> ); Query OK, 0 rows affected (1.12 sec)
使用插入命令在该表中插入一些记录。查询如下 −
mysql> insert into combineTwoColumnsDemo values(101,'John',23); Query OK, 1 row affected (0.16 sec) mysql> insert into combineTwoColumnsDemo values(102,'Carol',20); Query OK, 1 row affected (0.14 sec) mysql> insert into combineTwoColumnsDemo values(103,'Bob',25); Query OK, 1 row affected (0.13 sec) mysql> insert into combineTwoColumnsDemo values(104,'Mike',26); Query OK, 1 row affected (0.18 sec) mysql> insert into combineTwoColumnsDemo values(105,NULL,23); Query OK, 1 row affected (0.22 sec) mysql> insert into combineTwoColumnsDemo values(105,'Maxwell',NULL); Query OK, 1 row affected (0.15 sec)
现在,你可以使用select语句从该表中显示所有记录。查询如下 −
mysql> select *from combineTwoColumnsDemo;
以下是输出
+--------+----------+---------+ | UserId | UserName | UserAge | +--------+----------+---------+ | 101 | John | 23 | | 102 | Carol | 20 | | 103 | Bob | 25 | | 104 | Mike | 26 | | 105 | NULL | 23 | | 105 | Maxwell | NULL | +--------+----------+---------+ 6 rows in set (0.00 sec)
将两列合并为单一列的查询如下
mysql> SELECT UserName, -> UserAge, -> COALESCE(UserName, UserAge) AS Combine_UserName_UserAge -> FROM combineTwoColumnsDemo;
以下是输出
+----------+---------+--------------------------+ | UserName | UserAge | Combine_UserName_UserAge | +----------+---------+--------------------------+ | John | 23 | John | | Carol | 20 | Carol | | Bob | 25 | Bob | | Mike | 26 | Mike | | NULL | 23 | 23 | | Maxwell | NULL | Maxwell | +----------+---------+--------------------------+ 6 rows in set (0.00 sec)
广告