使用 MySQL CONCAT 将特定列值与相应记录合并
首先,我们创建一个表 -
mysql> create table DemoTable ( FirstName varchar(100), CountryName varchar(100) ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('Adam','US'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('David','AUS'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Chris','UK'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('John','US'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values('Carol','AUS'); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+-----------+-------------+ | FirstName | CountryName | +-----------+-------------+ | Adam | US | | David | AUS | | Chris | UK | | John | US | | Carol | AUS | +-----------+-------------+ 5 rows in set (0.00 sec)
以下是对特定列值与相应记录进行合并的查询 -
mysql> select concat(FirstName,' ',CountryName) AS NameWithCountry from DemoTable having NameWithCountry LIKE '%John%';
这将生成以下输出 -
+-----------------+ | NameWithCountry | +-----------------+ | John US | +-----------------+ 1 row in set (0.00 sec)
广告