MySQL 如何从一个表中选择字段并插入到另一个表中

MySQL 如何从一个表中选择字段并插入到另一个表中

首先让我们创建一个表 –

mysql> create table DemoTable1
   -> (
   -> StudentId int,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.64 sec)

使用插入命令将一些记录插入到表中 –

mysql> insert into DemoTable1 values(10,'John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable1 values(11,'Chris');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable1;

阅读更多:MySQL 教程

输出

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | John        |
| 11        | Chris       |
+-----------+-------------+
2 rows in set (0.00 sec)

以下是创建第二个表的查询 –

mysql> create table DemoTable2
   -> (
   -> CustomerId int,
   -> CustomerName varchar(100)
   -> );
Query OK, 0 rows affected (0.82 sec)

这里是从一个表中选择字段并插入到另一个表中的查询 –

mysql> insert into DemoTable2(CustomerId,CustomerName) select StudentId,StudentName from DemoTable1 where StudentId=11;
Query OK, 1 row affected (0.20 sec)
Records: 1 Duplicates: 0 Warnings: 0

让我们再次检查第二个表中的所有记录 –

mysql> select *from DemoTable2;

输出

+------------+--------------+
| CustomerId | CustomerName |
+------------+--------------+
| 11         | Chris        |
+------------+--------------+
1 row in set (0.00 sec)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程