從MySQL查詢結果填充表?
要從查詢結果填充表,請使用以下語法:
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)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP