從 MySQL 中提取資料的最高效方式是什麼以便用重複值進行格式化?
為此,你可以使用 GROUP_CONCAT()。我們首先建立一個表 -
mysql> create table DemoTable1561 -> ( -> StudentName varchar(20), -> Title text -> ); Query OK, 0 rows affected (0.60 sec)
使用 insert 命令向表中插入一些記錄 -
mysql> insert into DemoTable1561 values('Adam','Learning Java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1561 values('Bob','Learning C');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1561 values('Adam','Learning Spring and Hibernate Framework');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1561 values('Carol','Learning MySQL from basic');
Query OK, 1 row affected (0.30 sec)使用 select 語句顯示錶中的所有記錄 -
mysql> select * from DemoTable1561;
這將產生以下輸出 -
+-------------+-----------------------------------------+ | StudentName | Title | +-------------+-----------------------------------------+ | Adam | Learning Java | | Bob | Learning C | | Adam | Learning Spring and Hibernare Framework | | Carol | Learning MySQL from basic | +-------------+-----------------------------------------+ 4 rows in set (0.00 sec)
以下是要從 MySQL 中提取資料並進行格式化的查詢 -
mysql> select StudentName,group_concat(Title separator ',') as FormattedOutput from DemoTable1561 -> group by StudentName;
這將產生以下輸出 -
+-------------+-------------------------------------------------------+ | StudentName | FormattedOutput | +-------------+-------------------------------------------------------+ | Adam | Learning Java,Learning Spring and Hibernate Framework | | Bob | Learning C | | Carol | Learning MySQL from basic | +-------------+-------------------------------------------------------+ 3 rows in set (0.00 sec)
廣告
資料結構
網路技術
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
JavaScript
PHP