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

รวมค่าคอลัมน์ที่มี ID ซ้ำด้วย GROUP_CONCAT คั่น Slash ใน MySQL

บทความนี้สาธิตการใช้ GROUP_CONCAT() ร่วมกับ GROUP BY เพื่อรวมค่า ProductPrice ของ ProductId เดียวกันเป็นสตริงเดียว คั่นด้วย Slash (/)

สร้างตารางและข้อมูลราคาสินค้า (มี ProductId ซ้ำ)

mysql> CREATE TABLE DemoTable764(
    ProductId INT, ProductPrice INT
);
Query OK, 0 rows affected (0.56 sec)

mysql> INSERT INTO DemoTable764 VALUES(101, 10000), (102, 1090), (103, 4000), (102, 3450), (101, 20000), (104, 50000);

คิวรี GROUP_CONCAT คั่น Slash

mysql> SELECT ProductId, 
    GROUP_CONCAT(ProductPrice SEPARATOR '/') AS ProductPrice 
FROM DemoTable764 
GROUP BY ProductId;

ผลลัพธ์

+-----------+---------------+
| ProductId | ProductPrice  |
+-----------+---------------+
| 101       | 10000/20000   |
| 102       | 1090/3450     |
| 103       | 4000          |
| 104       | 50000         |
+-----------+---------------+

คำอธิบาย:

  • GROUP BY ProductId - จัดกลุ่มตาม ID สินค้า
  • GROUP_CONCAT(ProductPrice SEPARATOR '/') - รวมราคาในกลุ่มเดียวกัน คั่นด้วย /
  • Default Separator คือ Comma (,) ใช้ SEPARATOR 'custom' เปลี่ยนได้
  • สามารถเพิ่ม ORDER BY ProductPrice ใน GROUP_CONCAT: GROUP_CONCAT(ProductPrice ORDER BY ProductPrice SEPARATOR '/')

ข้อจำกัด: group_concat_max_len (Default 1024 bytes) จำกัดความยาวผลลัพธ์ → ต้องเพิ่มด้วย SET SESSION group_concat_max_len = 1000000; สำหรับข้อมูลเยอะ