Cú pháp INSERT với SELECT trong MySQL
INSERT INTO ten_bang(cot1, cot2, cot3, ...N) SELECT gia_tri1, gia_tri2, gia_tri3, ...N;
Ví dụ minh họa
Tạo bảng:
mysql> create table DemoTable1603 (
StudentId int,
StudentName varchar(20),
StudentMarks int
);
Query OK, 0 rows affected (0.50 sec)
Chèn dữ liệu bằng SELECT:
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; mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 103,'Bob',67;
Kết quả
+-----------+-------------+--------------+ | StudentId | StudentName | StudentMarks | +-----------+-------------+--------------+ | 101 | John | 45 | | 102 | Adam | 76 | | 103 | Bob | 67 | +-----------+-------------+--------------+ 3 rows in set (0.00 sec)
Ứng dụng thực tế: Cú pháp này rất hữu ích khi cần sao chép dữ liệu từ bảng này sang bảng khác, hoặc chèn dữ liệu được tính toán từ truy vấn con.