要使用select插入记录,请使用INSERT INTO SELECT语句。让我们首先创建一个表-
mysql> create table DemoTable1 -> ( -> Id int, -> FirstName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(101,'Chris'); mysql> insert into DemoTable1 values(NULL,'Bob'); mysql> insert into DemoTable1 values(NULL,NULL); mysql> insert into DemoTable1 values(102,'David');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable1;
这将产生以下输出-
+------+-----------+ | Id | FirstName | +------+-----------+ | 101 | Chris | | NULL | Bob | | NULL | NULL | | 102 | David | +------+-----------+ 4 rows in set (0.00 sec)
这是创建第二个表的查询。
mysql> create table DemoTable2 -> ( -> StudentId int, -> StudentName varchar(20) -> );
这是使用SELECT语句插入记录的查询-
mysql> insert into DemoTable2 -> select Id,FirstName from DemoTable1 -> where Id IS NOT NULL and FirstName IS NOT NULL; Records: 2 Duplicates: 0 Warnings: 0
使用select语句显示表中的所有记录-
mysql> select *from DemoTable2;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 102 | David | +-----------+-------------+ 2 rows in set (0.00 sec)