MySQL 查詢如何基於對應列中值為 1 的資料進行分組連線並將其放入單行?


為此,請使用 GROUP_CONCAT() 函式。對於僅包含 1 的值,可以使用 MySQL 的 WHERE 子句。首先,讓我們建立一個表:

mysql> create table DemoTable
(
   PlayerName varchar(40),
   PlayerStatus tinyint(1)
);
Query OK, 0 rows affected (0.60 sec)

使用 INSERT 命令在表中插入一些記錄:

mysql> insert into DemoTable values('Chris',1);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David',0);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Sam',1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Carol',1);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Bob',0);
Query OK, 1 row affected (0.14 sec)

使用 SELECT 語句顯示錶中的所有記錄:

mysql> select *from DemoTable;

這將產生以下輸出:

+------------+--------------+
| PlayerName | PlayerStatus |
+------------+--------------+
| Chris      |            1 |
| David      |            0 |
| Sam        |            1 |
| Carol      |            1 |
| Bob        |            0 |
+------------+--------------+
5 rows in set (0.00 sec)

以下是基於對應列中值為 1 的資料進行分組連線並將其放入單行的查詢:

mysql> select group_concat(PlayerName) from DemoTable where PlayerStatus=1;

這將產生以下輸出:

+--------------------------+
| group_concat(PlayerName) |
+--------------------------+
| Chris,Sam,Carol          |
+--------------------------+
1 row in set (0.00 sec)

更新於: 2019年10月9日

91 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.