如何使用 MySQL 将两个列值连接到一个单列中。结果列值应以连字符分隔
我们首先创建一个表 −
mysql> create table DemoTable835( CountryCode int, CountryName varchar(100) ); Query OK, 0 rows affected (0.63 sec)
使用插入命令在此表中插入一些记录 −
mysql> insert into DemoTable835 values(100,'US'); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable835 values(101,'UK'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable835 values(102,'AUS'); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable835 values(103,'ENG'); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中所有记录 −
mysql> select *from DemoTable835;
这将生成以下输出 −
+-------------+-------------+ | CountryCode | CountryName | +-------------+-------------+ | 100 | US | | 101 | UK | | 102 | AUS | | 103 | ENG | +-------------+-------------+ 4 rows in set (0.00 sec)
以下是将两个列值连接成一个单列的查询 −
mysql> select concat(CountryCode,'-',CountryName) from DemoTable835;
这将生成以下输出 −
+-------------------------------------+ | concat(CountryCode,'-',CountryName) | +-------------------------------------+ | 100-US | | 101-UK | | 102-AUS | | 103-ENG | +-------------------------------------+ 4 rows in set (0.00 sec)
广告