在 MySQL 中,如何从一个表中 SELECT 字段并 INSERT 到另一个表中?
mysqlmysqli database更新于 2025/9/11 16:12:17
首先我们创建一个表 −
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)
以下是从一个表中 SELECT 字段并 INSERT 到另一个表的查询 −
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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

