在 MySQL 中組合 INSERT、VALUES 和 SELECT


您可以使用以下語法將 insert、values 和 select 語句組合在一起

insert into yourFirstTableName(yourColumnName1,yourColumnName2,.......N)
select yourColumnName1,yourColumnName2,.......N
from yourSecondTableName where yourCondition;

為了理解上述語法,讓我們建立兩個表,其中第一個表將從第二個表中獲取記錄。

讓我們建立一個不包含任何記錄的表。建立表的查詢如下

mysql> create table CombiningInsertValuesSelect
   -> (
   -> EmployeeId varchar(10),
   -> EmployeeName varchar(100),
   -> EmployeeAge int
   -> );
Query OK, 0 rows affected (6.95 sec)

現在您可以建立包含一些記錄的第二個表。建立表的查詢如下

mysql> create table getAllValues
   -> (
   -> Id varchar(100),
   -> Name varchar(100),
   -> Age int
   -> );
Query OK, 0 rows affected (1.12 sec)

使用 insert 命令向名為“getAllValues”的第二個表中插入記錄。查詢如下

mysql> insert into getAllValues values('EMP-1','John',26);
Query OK, 1 row affected (0.86 sec)

mysql> insert into getAllValues values('EMP-2','Carol',22);
Query OK, 1 row affected (0.36 sec)

mysql> insert into getAllValues values('EMP-3','Sam',24);
Query OK, 1 row affected (0.28 sec)

mysql> insert into getAllValues values('EMP-4','David',27);
Query OK, 1 row affected (0.25 sec)

mysql> insert into getAllValues
values('EMP-5','Bob',21);
Query OK, 1 row affected (0.75 sec)

現在您可以使用 select 語句從表中顯示所有記錄。查詢如下

mysql> select *from getAllValues;

以下是輸出

+-------+-------+------+
| Id    | Name  | Age  |
+-------+-------+------+
| EMP-1 | John  |   26 |
| EMP-2 | Carol |   22 |
| EMP-3 | Sam   |   24 |
| EMP-4 | David |   27 |
| EMP-5 | Bob   |   21 |
+-------+-------+------+
5 rows in set (0.00 sec)

以下是 MySQL 中 insert、values 和 select 的用法。查詢如下

mysql> insert into CombiningInsertValuesSelect(EmployeeId,EmployeeName,EmployeeAge)
   -> select Id,Name,Age from getAllValues where Id='EMP-4';
Query OK, 1 row affected (0.23 sec)
Records: 1 Duplicates: 0 Warnings: 0

現在檢查是否存在該記錄表中或使用語句選擇。查詢如下

mysql> select *from CombiningInsertValuesSelect;

以下是輸出

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
| EMP-4      | David        | 27          |
+------------+--------------+-------------+
1 row in set (0.00 sec)

更新於:2019 年 7 月 30 日

1K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.