如何在 MySQL 中連線欄位?


要在 MySQL 中連線欄位,可以使用 GROUP_CONCAT() 以及 GROUP BY。我們首先建立一個表格 -

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(30),
   StudentScore int
   );
Query OK, 0 rows affected (0.51 sec)

使用 insert 指令在表格中插入記錄 -

mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',70);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',50);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('David',60);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',99);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('David',88);
Query OK, 1 row affected (0.18 sec)

使用 select 語句在表格中顯示所有記錄 -

mysql> select * from DemoTable;

這將產生以下輸出 -

+-----------+-------------+--------------+
| StudentId | StudentName | StudentScore |
+-----------+-------------+--------------+
| 1         | Bob         | 80           |
| 2         | Bob         | 80           |
| 3         | Chris       | 90           |
| 4         | Chris       | 70           |
| 5         | Bob         | 50           |
| 6         | David       | 60           |
| 7         | Chris       | 99           |
| 8         | David       | 88           |
+-----------+-------------+--------------+
8 rows in set (0.00 sec)

以下是在 MySQL 中連線欄位的查詢 -

mysql> select
StudentName, group_concat(StudentScore separator ',') as Score
from DemoTable
group by StudentName;

這將產生以下輸出 -

+-------------+----------+
| StudentName | Score    |
+-------------+----------+
| Bob         | 80,80,50 |
| Chris       | 90,70,99 |
| David       | 60,88    |
+-------------+----------+
3 rows in set (0.24 sec)

更新於:2019-07-30

306次瀏覽

開啟您的 職業

完成課程後獲得認證

開始
廣告