从数据库表中选择一些数据,然后使用MySQL插入同一数据库的另一个表中

要将数据从一个表插入另一个表,请使用INSERT INTO语句。让我们首先创建一个表-

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

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

mysql> insert into DemoTable1 values(101,'Chris',24);
mysql> insert into DemoTable1 values(102,'David',28);

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

mysql> select * from DemoTable1;

这将产生以下输出-

+------+-----------+------+
| Id   | FirstName | Age  |
+------+-----------+------+
|  101 | Chris     |   24 |
|  102 | David     |   28 |
+------+-----------+------+
2 rows in set (0.00 sec)

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

pre class="prettyprint notranslate" >
mysql> create table DemoTable2
     (
     EmployeeId int,
     EmployeeName varchar(20),
     EmployeeAge int
     );

以下是从一个数据库表中选择一些数据并插入同一数据库中另一个表的查询-

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

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

mysql> select * from DemoTable2;

这将产生以下输出-

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|        102 | David        |          28 |
+------------+--------------+-------------+
1 row in set (0.00 sec)