MySQL 查询将记录从一个表复制到具有不同列的另一个表
mysqlmysqli database
为此,您可以使用 INSERT INTO SELECT 语句。让我们首先创建一个表 −
mysql> create table DemoTable1900 ( ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(20), ClientAge int default 29 ) auto_increment=1000; Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1900(ClientName,ClientAge) values('Chris',45); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1900(ClientName,ClientAge) values('David',29); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1900(ClientName,ClientAge) values('Mike',37); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1900(ClientName) values('Sam'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1900;
这将产生以下输出 −
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 1000 | Chris | 45 | | 1001 | David | 29 | | 1002 | Mike | 37 | | 1003 | Sam | 29 | +----------+------------+-----------+ 4 rows in set (0.00 sec)
这是创建第二个表的查询 −
mysql> create table DemoTable1901 ( EmployeeId int, EmployeeName varchar(20), EmployeeAge int ); Query OK, 0 rows affected (0.00 sec)
以下查询用于将记录从一个表复制到具有不同列的另一个表 −
mysql> insert into DemoTable1901(EmployeeId,EmployeeName,EmployeeAge) select ClientId,ClientName, ClientAge from DemoTable1900; Query OK, 4 rows affected (0.00 sec) Records: 4 Duplicates: 0 Warnings: 0
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1901;
这将产生以下输出 −
+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1000 | Chris | 45 | | 1001 | David | 29 | | 1002 | Mike | 37 | | 1003 | Sam | 29 | +------------+--------------+-------------+ 4 rows in set (0.00 sec)