如何在 MySQL 中从一个表中选择字段并插入到另一个表中?
首先让我们创建一个表 -
mysql> create table DemoTable1 -> ( -> StudentId int, -> StudentName varchar(20) -> ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令在表中插入一些记录 -
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;
输出
+-----------+-------------+ | 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)
广告