如何顯示用逗號分隔的 MySQL 列中的資料?


你可以使用 MySQL 的 GROUP_CONCAT() 函式將結果顯示為逗號分隔的列表。我們首先建立一個表 -

mysql> create table DemoTable
   (
   Value int
   );
Query OK, 0 rows affected (0.26 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(50);
Query OK, 1 row affected (0.07 sec)

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

mysql> select *from DemoTable;

這將產生以下輸出 -

+-------+
| Value |
+-------+
| 10    |
| 20    |
| 30    |
| 40    |
| 50    |
+-------+
5 rows in set (0.00 sec)

以下是顯示用逗號分隔的列內資料的查詢。

mysql> SELECT GROUP_CONCAT(Value) FROM DemoTable;

這將產生以下輸出 -

+---------------------+
| GROUP_CONCAT(Value) |
+---------------------+
| 10,20,30,40,50      |
+---------------------+
1 row in set (0.00 sec)

更新於: 30-Jul-2019

572 瀏覽量

開啟你的職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.