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

INSERT ข้อมูลจากหลายตารางใน MySQL ด้วย INSERT INTO SELECT และ CROSS JOIN

ใช้ INSERT INTO ... SELECT ร่วมกับการ Join หลายตาราง (ตัวอย่างใช้ Cross Join / Cartesian Product) เพื่อรวมข้อมูลจากตารางแยกกัน

ตัวอย่าง: รวมชื่อจากตาราง 1 และ อายุจากตาราง 2

ตาราง 1: ชื่อ

mysql> create table DemoTable1943 (Name varchar(20));
mysql> insert into DemoTable1943 values('Chris'),('Robert');
mysql> select * from DemoTable1943;
+--------+
| Name   |
+--------+
| Chris  |
| Robert |
+--------+
2 rows in set

ตาราง 2: อายุ

mysql> create table DemoTable1944 (Age int);
mysql> insert into DemoTable1944 values(23),(26);
mysql> select * from DemoTable1944;
+------+
| Age  |
+------+
|   23 |
|   26 |
+------+
2 rows in set

ตาราง 3: ตารางปลายทาง (รวม)

mysql> create table DemoTable1945 (StudentName varchar(20), StudentAge int);

คิวรี INSERT จาก 2 ตาราง (Cross Join)

mysql> insert into DemoTable1945(StudentName, StudentAge) 
    -> select tbl1.Name, tbl2.Age 
    -> from DemoTable1943 tbl1, DemoTable1944 tbl2;

Query OK, 4 rows affected (2 × 2 = 4 แถว)

ผลลัพธ์: Cartesian Product (ทุกคู่)

mysql> select * from DemoTable1945;
+-------------+------------+
| StudentName | StudentAge |
+-------------+------------+
| Chris       |         23 |
| Robert      |         23 |
| Chris       |         26 |
| Robert      |         26 |
+-------------+------------+
4 rows in set (0.00 sec)

คำอธิบายและรูปแบบอื่น

  • Comma Join (เก่า): FROM tbl1, tbl2 = Cross Join
  • Explicit JOIN (แนะนำ):
    INSERT INTO DemoTable1945(StudentName, StudentAge)
    SELECT tbl1.Name, tbl2.Age
    FROM DemoTable1943 tbl1
    CROSS JOIN DemoTable1944 tbl2;
  • INNER JOIN (ถ้ามีเงื่อนไขเชื่อม): ON tbl1.id = tbl2.id
  • UNION ALL (ถ้าตารางโครงสร้างเหมือนกัน): รวมแถวแนวตั้ง

หมายเหตุ: Cross Join สร้างแถวมากเร็ว (n×m) ใช้謹慎กับตารางใหญ่