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

การใช้ INSERT กับ SELECT ใน MySQL

ไวยากรณ์ INSERT ... SELECT

insert into yourTableName(yourColumnName1,yourColumnName2,...) 
select yourValue1,yourValue2,...;

ตัวอย่างสร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1603 ( 
    -> StudentId int, 
    -> StudentName varchar(20), 
    -> StudentMarks int 
    -> ); 
Query OK, 0 rows affected (0.50 sec)
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 101,'John',45; 
Query OK, 1 row affected (0.17 sec) 
Records: 1  Duplicates: 0  Warnings: 0 
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 102,'Adam',76; 
Query OK, 1 row affected (0.11 sec) 
Records: 1  Duplicates: 0  Warnings: 0 
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 103,'Bob',67; 
Query OK, 1 row affected (0.31 sec) 
Records: 1  Duplicates: 0  Warnings: 0

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable1603;
+-----------+-------------+--------------+ 
| StudentId | StudentName | StudentMarks | 
+-----------+-------------+--------------+ 
|       101 | John        |           45 | 
|       102 | Adam        |           76 | 
|       103 | Bob         |           67 | 
+-----------+-------------+--------------+ 
3 rows in set (0.00 sec)

รูปแบบนี้เหมาะสำหรับการคัดลอกข้อมูลจากตารางอื่นหรือคำนวณค่าก่อน insert ได้ในคำสั่งเดียว