透過一列進行分組,並使用分隔符在 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)

更新於: 2019 年 09 月 10 日

1 千次以上瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.