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

MySQL: แทรกหลายแถวพร้อมกันในคำสั่ง INSERT เดียว

รูปแบบ INSERT หลายแถว

ใช้คอมมา (,) คั่นชุดค่าแต่ละชุดในคำสั่ง INSERT เดียว:

INSERT INTO table (col1, col2) 
VALUES (val1, val2), (val3, val4), (val5, val6), ...;

ตัวอย่าง: แทรก 5 นักเรียนพร้อมกัน

mysql> create table DemoTable811(
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    StudentName varchar(100),
    StudentAge int );
Query OK, 0 rows affected (0.54 sec)
mysql> insert into DemoTable811(StudentName,StudentAge) 
values('Chris',21),('Robert',22),('David',20),('Bob',19),('Carol',23);
Query OK, 5 rows affected (0.14 sec)
Records: 5  Duplicates: 0  Warnings: 0

ผลลัพธ์

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | Chris       | 21         |
| 2         | Robert      | 22         |
| 3         | David       | 20         |
| 4         | Bob         | 19         |
| 5         | Carol       | 23         |
+-----------+-------------+------------+

ข้อดีของ Multi-row INSERT

  • เร็วกว่า INSERT หลายคำสั่ง (ลด Round-trip, Parsing, Lock overhead)
  • Atomic - ทั้งหมดสำเร็จ หรือล้มเหลวทั้งหมด (ถ้าไม่มี IGNORE)
  • สะดวก เขียนโค้ดสั้นกว่า

ข้อจำกัด

  • ขนาด Packet ต้องไม่เกิน max_allowed_packet (Default ~4-64MB)
  • จำนวนแถวมากเกินไป ควรแบทช์ (Batch) ทีละหลายพัน/หมื่นแถว

สรุป

ใช้ INSERT ... VALUES (...), (...), ... สำหรับแทรกหลายแถวพร้อมกัน เร็วและมีประสิทธิภาพกว่า INSERT แยกหลายคำสั่ง