在 MySQL 中按一列分组并使用分隔符显示另一列中的相应记录

mysqlmysqli database

为此,请将 GROUP_CONCAT() 与 GROUP BY 一起使用。此处,GROUP_CONCAT() 用于将多行数据连接到一个字段中。

首先我们创建一个表 −

mysql> create table DemoTable
(
   PlayerId int,
   ListOfPlayerName varchar(30)
);
Query OK, 0 rows affected (0.52 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(100,'Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(100,'Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(102,'Carol');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Tom');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(102,'John');
Query OK, 1 row affected (0.12 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+----------+------------------+
| PlayerId | ListOfPlayerName |
+----------+------------------+
|      100 | Chris            |
|      101 | David            |
|      100 | Bob              |
|      100 | Sam              |
|      102 | Carol            |
|      101 | Tom              |
|      102 | John             |
+----------+------------------+
7 rows in set (0.00 sec)

以下查询按一列分组并使用分隔符显示另一列的结果 −

mysql> select PlayerId,group_concat(ListOfPlayerName separator '/') as AllPlayerNameWithSameId from DemoTable
   group by PlayerId;

这将产生以下输出 −

+----------+-------------------------+
| PlayerId | AllPlayerNameWithSameId |
+----------+-------------------------+
|      100 | Chris/Bob/Sam           |
|      101 | David/Tom               |
|      102 | Carol/John              |
+----------+-------------------------+
3 rows in set (0.00 sec)

相关文章