在 MySQL 中从查询结果填充表格?
mysqlmysqli database
要从查询结果填充表格,请使用以下语法:
INSERT yourTableName(yourColumnName1,yourColumnName2,yourColumnName3,..........N) SELECT yourColumnName1,yourColumnName2,yourColumnName3,..........N FROM yourAnotherTableName;
为了理解上述语法,让我们创建一个表格。第一个表格如下所示,其中包含一些记录。创建表格的查询如下:
mysql> create table PopulateTableDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Amount int, -> ArrivalDateTime datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.68 sec)
现在您可以使用 insert 命令在表中插入一些记录。查询如下:
mysql> create table PopulateTableDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Amount int, -> ArrivalDateTime datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下:
mysql> insert into PopulateTableDemo(Name,Amount,ArrivalDateTime) values('John',456,'2018-02-4'); Query OK, 1 row affected (0.17 sec) mysql> insert into PopulateTableDemo(Name,Amount,ArrivalDateTime) values('Carol',1000,'2019-10-21'); Query OK, 1 row affected (0.17 sec) mysql> insert into PopulateTableDemo(Name,Amount,ArrivalDateTime) values('Sam',970,'2019-07-25'); Query OK, 1 row affected (0.14 sec) mysql> insert into PopulateTableDemo(Name,Amount,ArrivalDateTime) values('Larry',1050,'2015-10-28'); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录。查询如下:
mysql> select *from PopulateTableDemo;
输出结果如下:
+----+-------+--------+---------------------+ | Id | Name | Amount | ArrivalDateTime | +----+-------+--------+---------------------+ | 1 | John | 456 | 2018-02-04 00:00:00 | | 2 | Carol | 1000 | 2019-10-21 00:00:00 | | 3 | Sam | 970 | 2019-07-25 00:00:00 | | 4 | Larry | 1050 | 2015-10-28 00:00:00 | +----+-------+--------+---------------------+ 4 rows in set (0.00 sec)
现在您可以创建第二个表并填充上表中的值。创建第二个表的查询如下:
mysql> create table PopulateQueryFromAnotherTable -> ( -> Id int NOT NULL AUTO_INCREMENT, -> UserName varchar(20), -> Salary int, -> DepartureDateTime datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.30 sec)
以下是从第一个表 PopulateTableDemo 填充值到 PopulateQueryFromAnotherTable 的查询:
mysql> insert PopulateQueryFromAnotherTable(UserName,Salary,DepartureDateTime) -> select Name,Amount,ArrivalDateTime from PopulateTableDemo; Query OK, 4 rows affected (0.15 sec) Records: 4 Duplicates: 0 Warnings: 0
现在使用 select 语句检查第二个表记录。查询如下:
mysql> select *from PopulateQueryFromAnotherTable;
输出结果如下:
+----+----------+--------+---------------------+ | Id | UserName | Salary | DepartureDateTime | +----+----------+--------+---------------------+ | 1 | John | 456 | 2018-02-04 00:00:00 | | 2 | Carol | 1000 | 2019-10-21 00:00:00 | | 3 | Sam | 970 | 2019-07-25 00:00:00 | | 4 | Larry | 1050 | 2015-10-28 00:00:00 | +----+----------+--------+---------------------+ 4 rows in set (0.00 sec)