在 MySQL 中通过 MySQL SELECT 将值插入到表中?
对于此问题,使用 INSERT INTO SELECT 语句。让我们先创建一个表 −
mysql> create table DemoTable1 -> ( -> Id int, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (1.72 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1 values(100,'Chris',24); Query OK, 1 row affected (0.61 sec) mysql> insert into DemoTable1 values(101,'Adam',23); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1 values(102,'John',25); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1 values(103,'Carol',26); Query OK, 1 row affected (0.26 sec)
使用 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 -> ); Query OK, 0 rows affected (1.63 sec)
以下是将值从 MySQL select 插入到 DemoTable2 中的查询 −
mysql> insert into DemoTable2(EmployeeId,EmployeeFirstName,EmployeeAge) select Id,Name,Age from DemoTable1 where Id=101; Query OK, 1 row affected (0.17 sec) Records: 1 Duplicates: 0 Warnings: 0
让我们检查表记录 −
mysql> select * from DemoTable2;
以下是创建第二个表的查询 −
+------------+-------------------+-------------+ | EmployeeId | EmployeeFirstName | EmployeeAge | +------------+-------------------+-------------+ | 101 | Adam | 23 | +------------+-------------------+-------------+ 1 row in set (0.00 sec)
广告