透過一列進行分組,並使用分隔符在 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)
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP