ใช้ INSERT INTO ... SELECT ... UNION ALL ... เพื่อเพิ่มหลายแถวใน Statement เดียว โดยสร้าง Virtual Rows จากค่าคงที่
Syntax
INSERT INTO table_name (col1, col2, col3) SELECT val1, val2, val3 UNION ALL SELECT val4, val5, val6 UNION ALL SELECT val7, val8, val9; ...
ตัวอย่างการใช้งาน
1. สร้างตาราง
mysql> create table DemoTable1936 (
-> StudentId int,
-> StudentName varchar(20),
-> StudentCountryName varchar(20)
-> ); Query OK, 0 rows affected (0.00 sec)
2. Insert 3 แถวพร้อมด้วย UNION ALL
mysql> insert into DemoTable1936(StudentId,StudentName,StudentCountryName)
-> select 1001 as StudentId, 'Chris' as StudentName, 'US' as StudentCountryName
-> union all
-> select 1002 as StudentId, 'Robert' as StudentName, 'UK' as StudentCountryName
-> union all
-> select 1003 as StudentId, 'David' as StudentName, 'AUS' as StudentCountryName;
Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0
3. ตรวจสอบผลลัพธ์
mysql> select * from DemoTable1936;
+-----------+-------------+--------------------+ | StudentId | StudentName | StudentCountryName | +-----------+-------------+--------------------+ | 1001 | Chris | US | | 1002 | Robert | UK | | 1003 | David | AUS | +-----------+-------------+--------------------+ 3 rows in set (0.00 sec)
UNION vs UNION ALL ใน INSERT
| คำสั่ง | พฤติกรรม | ใช้เมื่อ |
|---|---|---|
| UNION ALL | รวมทุกแถว รวมซ้ำได้ | Insert หลายแถวเร็ว ไม่ต้องเช็คซ้ำ |
| UNION | ลบแถวซ้ำ (Distinct) | ต้องการ Unique Rows ช้ากว่า |
วิธีอื่น: INSERT VALUES หลายแถว (MySQL Standard)
INSERT INTO DemoTable1936 (StudentId, StudentName, StudentCountryName) VALUES (1001, 'Chris', 'US'), (1002, 'Robert', 'UK'), (1003, 'David', 'AUS');
- Syntax นี้เป็นมาตรฐาน SQL รองรับ MySQL, PostgreSQL, SQL Server
- เร็วกว่าและอ่านง่ายกว่า UNION ALL สำหรับค่าคงที่
- แนะนำใช้วิธีนี้สำหรับ Bulk Insert ค่าคงที่
Insert จากตารางอื่นหลายตาราง
INSERT INTO target (a,b,c) SELECT a,b,c FROM table1 UNION ALL SELECT a,b,c FROM table2 UNION ALL SELECT a,b,c FROM table3;
สรุป: ใช้ INSERT INTO ... SELECT ... UNION ALL SELECT ... สำหรับ Insert หลายแถวจากค่าคงที่ แต่แนะนำ INSERT INTO ... VALUES (...), (...), (...) ซึ่งเป็นมาตรฐาน เร็วกว่า และอ่านง่ายกว่า