您可以使用以下语法组合插入,值和选择语句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
-> );
现在,您可以使用一些记录创建第二个表。创建表的查询如下mysql> create table getAllValues
-> (
-> Id varchar(100),
-> Name varchar(100),
-> Age int
-> );
使用insert命令在第二张表中插入名称为'getAllValues'的记录。查询如下mysql> insert into getAllValues values('EMP-1','John',26);
mysql> insert into getAllValues values('EMP-2','Carol',22);
mysql> insert into getAllValues values('EMP-3','Sam',24);
mysql> insert into getAllValues values('EMP-4','David',27);
mysql> insert into getAllValues
values('EMP-5','Bob',21);
现在,您可以使用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中使用插入,值和选择。查询如下mysql> insert into CombiningInsertValuesSelect(EmployeeId,EmployeeName,EmployeeAge)
-> select Id,Name,Age from getAllValues where Id='EMP-4';
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)