通过一列进行分组,并使用分隔符在 MySQL 中显示来自另一列的相应记录
为此,请在 GROUP BY 中使用 GROUP_CONCAT()。此处,使用 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)
广告