在 MySQL SELECT 子句中添加/连接文本值?
要在 select 子句中添加/连接文本值,可以使用 concat() 函数。
让我们创建一个表
mysql> create table ConcatenatingDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20), -> UserCountryName varchar(20) -> ); Query OK, 0 rows affected (0.82 sec)
现在,你可以使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('John','US'); Query OK, 1 row affected (0.14 sec) mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('Carol','UK'); Query OK, 1 row affected (0.13 sec) mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('Bob','AUS'); Query OK, 1 row affected (0.15 sec) mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('David','US'); Query OK, 1 row affected (0.29 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from ConcatenatingDemo;
以下是输出
+--------+----------+-----------------+ | UserId | UserName | UserCountryName | +--------+----------+-----------------+ | 1 | John | US | | 2 | Carol | UK | | 3 | Bob | AUS | | 4 | David | US | +--------+----------+-----------------+ 4 rows in set (0.00 sec)
这里有在 SELECT 子句中添加/连接文本值的查询
mysql> select concat(UserName,' belongs to ( ',UserCountryName,' )') as AddingTextDemo from ConcatenatingDemo;
以下是输出
+-------------------------+ | AddingTextDemo | +-------------------------+ | John belongs to ( US ) | | Carol belongs to ( UK ) | | Bob belongs to ( AUS ) | | David belongs to ( US ) | +-------------------------+ 4 rows in set (0.00 sec)
广告