通过MySQL SELECT从MySQL的另一个表插入表中的值?

为此,请使用INSERT INTO SELECT语句。让我们首先创建一个表-

mysql> create table DemoTable1
   -> (
   -> Id int,
   -> Name varchar(20),
   -> Age int
   -> );

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1 values(100,'Chris',24);
mysql> insert into DemoTable1 values(101,'Adam',23);
mysql> insert into DemoTable1 values(102,'John',25);
mysql> insert into DemoTable1 values(103,'Carol',26);

使用select语句显示表中的所有记录-

mysql> select * from DemoTable1;

这将产生以下输出-

+------+-------+------+
| Id   | Name | Age |
+------+-------+------+
|  100 | Chris |   24 |
|  101 | Adam  |   23 |
|  102 | John  |   25 |
|  103 | Carol |   26 |
+------+-------+------+
4 rows in set (0.00 sec)

这是创建第二个表的查询-

mysql> create table DemoTable2
   -> (
   -> EmployeeId int,
   -> EmployeeFirstName varchar(20),
   -> EmployeeAge int
   -> );

这是在MySQL的DemoTable2中插入值的查询,请从DemoTable1选择-

mysql> insert into DemoTable2(EmployeeId,EmployeeFirstName,EmployeeAge) select Id,Name,Age from DemoTable1 where Id=101;
Records: 1 Duplicates: 0 Warnings: 0

让我们检查表记录-

mysql> select * from DemoTable2;

这是创建第二个表的查询-

+------------+-------------------+-------------+
| EmployeeId | EmployeeFirstName | EmployeeAge |
+------------+-------------------+-------------+
|        101 | Adam              |          23 |
+------------+-------------------+-------------+
1 row in set (0.00 sec)