如何在 MySQL 中连接单个列的所有值?
你可以使用 group_concat() 以及 concat() 来连接单个列的所有值。我们首先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20) ); Query OK, 0 rows affected (0.73 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable(FirstName) values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(FirstName) values('Larry'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(FirstName) values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(FirstName) values('Robert'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(FirstName) values('David'); Query OK, 1 row affected (0.12 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Larry | | 3 | Chris | | 4 | Robert | | 5 | David | +----+-----------+ 5 rows in set (0.00 sec)
以下是连接 MySQL 中单个列的所有值的查询。
mysql> select group_concat(concat('"', FirstName, '"')) AS FirstName from DemoTable;
这将生成以下输出 -
+-----------------------------------------+ | FirstName | +-----------------------------------------+ | "John","Larry","Chris","Robert","David" | +-----------------------------------------+ 1 row in set (0.05 sec)
广告