如何将 MySQL 独特查询结果连接成一个字符串?
从 MySQL 使用 group_concat() 函数连接。我们先创建一个表 -
mysql> create table DemoTable -> ( -> Subject varchar(10) -> ); Query OK, 0 rows affected (0.43 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable values('C'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('C++'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('C++'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('MySQL'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement:
mysql> select *from DemoTable;
输出
这将产生以下输出 -
+---------+ | Subject | +---------+ | C | | C++ | | C++ | | MongoDB | | MySQL | | MongoDB | | MongoDB | | Java | | Java | +---------+ 9 rows in set (0.00 sec)
以下是用 MySQL 查询将 SQL 唯一查询结果连接成字符串 -
mysql> select group_concat(tbl.sub) from (select Subject sub from DemoTable group by Subject ) tbl;
输出
这将产生以下输出 -
+--------------------------+ | group_concat(tbl.sub) | +--------------------------+ | C,C++,MongoDB,MySQL,Java | +--------------------------+ 1 row in set (0.04 sec)
广告