如何使用單個 MySQL 查詢將行壓縮到逗號分隔列表?


要將行壓縮到逗號分隔列表,請使用 GROUP_CONCAT()。我們首先建立一個表 −

mysql> create table DemoTable
(
   Id int,
   Name varchar(40)
);
Query OK, 0 rows affected (0.52 sec)

使用 insert 命令將一些記錄插入表 −

mysql> insert into DemoTable values(100,'Chris Brown');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(101,'Adam Smith');
Query OK, 1 row affected (0.84 sec)
mysql> insert into DemoTable values(101,'John Doe');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(100,'David Miller');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(101,'Carol Taylor');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(103,'Bob Taylor');
Query OK, 1 row affected (0.20 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+------+--------------+
| Id   | Name         |
+------+--------------+
|  100 | Chris Brown  |
|  101 | Adam Smith   |
|  101 | John Doe     |
|  100 | David Miller |
|  101 | Carol Taylor |
|  103 | Bob Taylor   |
+------+--------------+
6 rows in set (0.00 sec)

以下是將行壓縮到逗號分隔列表的查詢 −

mysql> select Id,group_concat(Name) from DemoTable group by Id;

這將產生以下輸出 −

+------+----------------------------------+
| Id   | group_concat(Name)               |
+------+----------------------------------+
|  100 | Chris Brown,David Miller         |
|  101 | Adam Smith,John Doe,Carol Taylor |
|  103 | Bob Taylor                       |
+------+----------------------------------+
3 rows in set (0.00 sec)

更新日期:2019-10-10

555 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告