在MySQL中使用INSERT INTO SELECT和UNION执行多次插入
要执行多次插入,语法如下:
insert into yourTableName(yourColumnName1,yourColumnName2,yourColumnName3,..N) select yourValue1 as yourColumnName1,yourValue2 as yourColumnName2,yourValue3 as yourColumnName3,......N union select yourValue1 as yourColumnName1,yourValue2 as yourColumnName2,yourValue3 as yourColumnName3,......N . . N
要了解上述语法,让我们创建一个表-
create table DemoTable1936 ( StudentId int, StudentName varchar(20), StudentCountryName varchar(20) );
使用插入命令在表中插入一些记录-
insert into DemoTable1936(StudentId,StudentName,StudentCountryName) select 1001 as StudentId,'Chris' as StudentName,'US' as StudentCountryName union select 1002 as StudentId,'Robert' as StudentName,'UK' as StudentCountryName union select 1003 as StudentId,'David' as StudentName,'AUS' as StudentCountryName; Records: 3 Duplicates: 0 Warnings: 0
使用select语句显示表中的所有记录-
select * from DemoTable1936;
这将产生以下输出-
+-----------+-------------+--------------------+ | StudentId | StudentName | StudentCountryName | +-----------+-------------+--------------------+ | 1001 | Chris | US | | 1002 | Robert | UK | | 1003 | David | AUS | +-----------+-------------+--------------------+ 3 rows in set (0.00 sec)