Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

รวม CONCAT() และ GROUP_CONCAT() ในคิวรี MySQL เดียว

CONCAT() ต่อสตริงในแถวเดียว, GROUP_CONCAT() รวมสตริงหลายแถวเป็นหนึ่ง

สร้างตารางและเพิ่มข้อมูล (UserId 101 ซ้ำ 3 ครั้ง)

mysql> create table DemoTable799 ( UserId int, UserName varchar(100), UserAge int ); 
Query OK, 0 rows affected (0.56 sec)

mysql> insert into DemoTable799 values(101,'John',21); Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable799 values(102,'Chris',26); Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable799 values(101,'Robert',23); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable799 values(103,'David',24); Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable799 values(101,'Mike',29); Query OK, 1 row affected (0.18 sec)

คิวรี CONCAT ใน GROUP_CONCAT

mysql> select UserId, GROUP_CONCAT(CONCAT('MR.', UserName)) 
from DemoTable799 group by UserId;
+--------+---------------------------------------+
| UserId | GROUP_CONCAT(CONCAT('MR.', UserName)) |
+--------+---------------------------------------+
| 101    | MR.John,MR.Robert,MR.Mike             |
| 102    | MR.Chris                              |
| 103    | MR.David                              |
+--------+---------------------------------------+
3 rows in set (0.00 sec)

การทำงาน: 1) CONCAT('MR.', UserName) → 'MR.John' ต่อแถว 2) GROUP_CONCAT รวมตาม UserId