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

INSERT ข้อมูลจากตารางอื่นแบบ DISTINCT ไม่ซ้ำใน MySQL

เมื่อต้องการคัดลอกข้อมูลจากตารางหนึ่งไปอีกตาราง แต่ต้องการเฉพาะค่าที่ไม่ซ้ำกัน (Distinct) ให้ใช้ INSERT INTO ... SELECT DISTINCT ...

ตัวอย่างตารางต้นทาง (DemoTable1) มีค่าซ้ำ

mysql> create table DemoTable1 ( Value int ); 
Query OK, 0 rows affected (1.03 sec)
mysql> insert into DemoTable1 values(50); 
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1 values(10); 
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(10); 
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1 values(60); 
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1 values(50); 
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1 values(70); 
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1 values(50); 
Query OK, 1 row affected (0.14 sec)

ข้อมูลใน DemoTable1 (มีซ้ำ)

mysql> select * from DemoTable1;
+-------+
| Value |
+-------+
| 50    |
| 10    |
| 10    |
| 60    |
| 50    |
| 70    |
| 50    |
+-------+
7 rows in set (0.00 sec)

สร้างตารางปลายทาง

mysql> create table DemoTable2 ( Marks int ); 
Query OK, 0 rows affected (1.20 sec)

คำสั่ง INSERT SELECT DISTINCT

mysql> insert into DemoTable2(Marks) select distinct Value from DemoTable1; 
Query OK, 4 rows affected (0.18 sec)
Records: 4  Duplicates: 0  Warnings: 0

ผลลัพธ์ใน DemoTable2 (ไม่ซ้ำ)

mysql> select * from DemoTable2;
+-------+
| Marks |
+-------+
| 50    |
| 10    |
| 60    |
| 70    |
+-------+
4 rows in set (0.00 sec)

คำอธิบาย: SELECT DISTINCT Value จะคัดกรองค่าซ้ำออกก่อน แล้วค่อย INSERT เข้า DemoTable2 วิธีนี้เหมาะสำหรับสร้างตาราง Dimension Table หรือ Lookup Table จากข้อมูลดิบ (Raw Data)