使用 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
为了理解以上语法,我们创建一个表 −
mysql> create table DemoTable1936 ( StudentId int, StudentName varchar(20), StudentCountryName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用插入命令在表中插入一些记录 −
mysql> 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; Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0
使用 select 语句从表中显示所有记录 −
mysql> select * from DemoTable1936;
这将产生以下输出 −
+-----------+-------------+--------------------+ | StudentId | StudentName | StudentCountryName | +-----------+-------------+--------------------+ | 1001 | Chris | US | | 1002 | Robert | UK | | 1003 | David | AUS | +-----------+-------------+--------------------+ 3 rows in set (0.00 sec)
广告