为此,将GROUP_CONCAT()与GROUP BY一起使用。在这里,GROUP_CONCAT()用于将来自多行的数据连接到一个字段中。
让我们首先创建一个表-
create table DemoTable ( PlayerId int, ListOfPlayerName varchar(30) );
使用插入命令在表中插入一些记录-
insert into DemoTable values(100,'Chris'); insert into DemoTable values(101,'David'); insert into DemoTable values(100,'Bob'); insert into DemoTable values(100,'Sam'); insert into DemoTable values(102,'Carol'); insert into DemoTable values(101,'Tom'); insert into DemoTable values(102,'John');
使用select语句显示表中的所有记录-
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)
以下是按一列分组并用分隔符显示另一列的结果的查询-
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)