首頁 > 資料庫 > mysql教程 > 在 MySQL 中組合 INSERT、VALUES 和 SELECT

在 MySQL 中組合 INSERT、VALUES 和 SELECT

PHPz
發布: 2023-09-17 16:45:03
轉載
1437 人瀏覽過

在 MySQL 中组合 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)
登入後複製

使用插入指令在第二個表格中插入名為「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
登入後複製

現在使用 select 語句檢查記錄是否存在於表中。查詢如下

mysql> select *from CombiningInsertValuesSelect;
登入後複製

以下是輸出

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
| EMP-4      | David        | 27          |
+------------+--------------+-------------+
1 row in set (0.00 sec)
登入後複製
#

以上是在 MySQL 中組合 INSERT、VALUES 和 SELECT的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板