Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Gom nhóm theo một cột và hiển thị các bản ghi tương ứng từ cột khác với dấu phân cách trong MySQL

Mục tiêu

Sử dụng hàm GROUP_CONCAT() kết hợp với GROUP BY để nối chuỗi các giá trị từ nhiều hàng thành một trường, phân cách bằng ký tự tùy chọn.

1. Tạo bảng

mysql> create table DemoTable (
    PlayerId int,
    ListOfPlayerName varchar(30)
);
Query OK, 0 rows affected (0.52 sec)

2. Chèn dữ liệu

mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(101,'David'); Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(100,'Bob'); Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(100,'Sam'); Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(102,'Carol'); Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Tom'); Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(102,'John'); Query OK, 1 row affected (0.12 sec)

3. Xem dữ liệu gốc

mysql> select * from DemoTable;
+----------+------------------+
| PlayerId | ListOfPlayerName |
+----------+------------------+
| 100      | Chris            |
| 101      | David            |
| 100      | Bob              |
| 100      | Sam              |
| 102      | Carol            |
| 101      | Tom              |
| 102      | John             |
+----------+------------------+
7 rows in set (0.00 sec)

4. Truy vấn gom nhóm và nối chuỗi

mysql> select PlayerId, group_concat(ListOfPlayerName separator '/') as AllPlayerNameWithSameId
    from DemoTable group by PlayerId;

Kết quả:

+----------+-------------------------+
| PlayerId | AllPlayerNameWithSameId |
+----------+-------------------------+
| 100      | Chris/Bob/Sam           |
| 101      | David/Tom               |
| 102      | Carol/John              |
+----------+-------------------------+
3 rows in set (0.00 sec)

Giải thích: separator '/' chỉ định dấu phân cách; nếu bỏ qua, mặc định là dấu phẩy.