在 MySQL SELECT 中连接字段?
mysqlmysqli database
要在 MySQL SELECT 中连接字段,请使用 CONCAT() 函数,如以下语法所示。
SELECT CONCAT(yourColumnName1,’anyConcatenationString’),CONCAT(yourColumnName2,’anyC oncatenationString’),....N from yourTableName;
为了理解上述语法,让我们首先创建一个表。创建表的查询如下。
mysql> create table selectConcat -> ( -> StudentId int, -> StudentName varchar(100), -> StudentAge int -> ); Query OK, 0 rows affected (1.32 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into selectConcat values(1,'Carol',23); Query OK, 1 row affected (0.19 sec) mysql> insert into selectConcat values(2,'John',24); Query OK, 1 row affected (0.25 sec) mysql> insert into selectConcat values(3,'Adam',25); Query OK, 1 row affected (0.14 sec) mysql> insert into selectConcat values(4,'Bob',21); Query OK, 1 row affected (0.20 sec) mysql> insert into selectConcat values(5,'Sam',22); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from selectConcat;
以下是输出。
+-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | Carol | 23 | | 2 | John | 24 | | 3 | Adam | 25 | | 4 | Bob | 21 | | 5 | Sam | 22 | +-----------+-------------+------------+ 5 rows in set (0.00 sec)
在select语句中联系该字段。查询如下。
mysql> select concat(StudentId,' as an Id'),concat(StudentName,' as a Name') from selectConcat;
以下是输出。
+-------------------------------+----------------------------------+ | concat(StudentId,' as an Id') | concat(StudentName,' as a Name') | +-------------------------------+----------------------------------+ | 1 as an Id | Carol as a Name | | 2 as an Id | John as a Name | | 3 as an Id | Adam as a Name | | 4 as an Id | Bob as a Name | | 5 as an Id | Sam as a Name | +-------------------------------+----------------------------------+ 5 rows in set (0.00 sec)