使用单个 MySQL 查询中的两个 SELECT 语句将第一个表中的值插入第二个表中
mysqlmysqli database
要使用两个 SELECT 语句将第一个表中的值插入另一个表中,请使用 SUBQUERY。这样,您只需使用单个 MySQL 查询即可获得第二个表中的结果。让我们首先创建一个表−
mysql> create table DemoTable1 ( Name varchar(100), Score int ); Query OK, 0 rows affected (1.30 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1 values('Chris',45); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1 values('Bob',78); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1 values('David',98); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1 values('Carol',89); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable1;
这将产生以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 45 | | Bob | 78 | | David | 98 | | Carol | 89 | +-------+-------+ 4 rows in set (0.00 sec)
以下是创建第二个表的查询。
mysql> create table DemoTable2 ( StudentName varchar(100), StudentScore int ); Query OK, 0 rows affected (0.58 sec)
现在让我们编写一个 MySQL 查询,使用两个 SELECT 语句将第一个表中的值插入到第二个表中 −
mysql> insert into DemoTable2(StudentName,StudentScore) values((select Name from DemoTable1 where Score=98),(select Score from DemoTable1 where Name='David')); Query OK, 1 row affected (0.30 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable2; +-------------+--------------+ | StudentName | StudentScore | +-------------+--------------+ | David | 98 | +-------------+--------------+ 1 row in set (0.00 sec)