如何正确地在 MySQL 中使用 INSERT INTO … SELECT 来避免错误 1064?
首先,让我们创建一个表格 -
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstName varchar(100) -> ); Query OK, 0 rows affected (0.57 sec)
使用插入命令在表格中插入一些记录 -
mysql> insert into DemoTable1(FirstName) values('John'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1(FirstName) values('Chris'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示来自表格的所有记录 -
mysql> select *from DemoTable1;
以下会生成此输出 -
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Chris | +----+-----------+ 2 rows in set (0.00 sec)
现在,创建一个第二张表 -
mysql> create table DemoTable2 -> ( -> CustomerId int, -> CustomerName varchar(100) -> ); Query OK, 0 rows affected (0.43 sec)
现在,可以使用 INSERT INTO SELECT 命令在上述表中插入一些记录 -
mysql> insert into DemoTable2(CustomerId,CustomerName) -> select Id,FirstName from DemoTable1; Query OK, 2 rows affected (0.17 sec) Records: 2 Duplicates: 0 Warnings: 0
使用 select 语句显示来自表格的所有记录 -
mysql> select *from DemoTable2;
以下会生成此输出 -
+------------+--------------+ | CustomerId | CustomerName | +------------+--------------+ | 1 | John | | 2 | Chris | +------------+--------------+ 2 rows in set (0.00 sec)
广告