如何在 MySQL 中從一個結構不同的表向另一個表插入資料?
為此,使用 INSERT INTO SELECT 語句。我們先建立一個表 −
mysql> create table DemoTable1 -> ( -> PersonId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> PersonName varchar(20), -> PersonAge int, -> PersonCountryName varchar(20) -> ); Query OK, 0 rows affected (0.55 sec)
使用 insert 命令在表中插入一些記錄 −
mysql> insert into DemoTable1(PersonName,PersonAge,PersonCountryName) values('Chris Brown',24,'US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1(PersonName,PersonAge,PersonCountryName) values('John Doe',26,'UK');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1(PersonName,PersonAge,PersonCountryName) values('David Miller',23,'AUS');
Query OK, 1 row affected (0.10 sec)使用 select 語句顯示錶中的所有記錄 −
mysql> select * from DemoTable1;
這會產生以下輸出 −
+----------+--------------+-----------+-------------------+ | PersonId | PersonName | PersonAge | PersonCountryName | +----------+--------------+-----------+-------------------+ | 1 | Chris Brown | 24 | US | | 2 | John Doe | 26 | UK | | 3 | David Miller | 23 | AUS | +----------+--------------+-----------+-------------------+ 3 rows in set (0.00 sec)
下面是建立第二個表的查詢 −
mysql> create table DemoTable2 -> ( -> EmployeeId int, -> EmployeeFullName varchar(30), -> EmployeeAge int, -> EmployeeCountryName varchar(20), -> EmployeeSalary int default 20000 -> ); Query OK, 0 rows affected (0.52 sec)
下面是查詢用於從一個帶有不同結構的表向另一個表中插入資料 −
mysql> insert into DemoTable2(EmployeeId,EmployeeFullName,EmployeeAge,EmployeeCountryName) select PersonId,PersonName,PersonAge,PersonCountryName from DemoTable1; Query OK, 3 rows affected (0.26 sec) Records: 3 Duplicates: 0 Warnings: 0
使用 select 語句顯示錶中的所有記錄 −
mysql> select * from DemoTable1;
這會產生以下輸出 −
+------------+------------------+-------------+---------------------+----------------+ | EmployeeId | EmployeeFullName | EmployeeAge | EmployeeCountryName | EmployeeSalary | +------------+------------------+-------------+---------------------+----------------+ | 1 | Chris Brown | 24 | US | 20000 | | 2 | John Doe | 26 | UK | 20000 | | 3 | David Miller | 23 | AUS | 20000 | +------------+------------------+-------------+---------------------+----------------+ 3 rows in set (0.00 sec)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP