MySQL复制表-SELECT INTO FROM

Posted YY&BB姐姐的光阴故事

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL复制表-SELECT INTO FROM相关的知识,希望对你有一定的参考价值。

基础Table:

mysql> select * from staff;
+----+----------+-------+
| id | name     | slary |
+----+----------+-------+
|  3 | haofugui | 10000 |
|  4 | guoming  |  3500 |
|  5 | haotian  |  2900 |
+----+----------+-------+
3 rows in set (0.00 sec)

mysql> describe staff;
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| id    | int(11)  | NO   | PRI | NULL    | auto_increment |
| name  | char(20) | YES  |     | NULL    |                |
| slary | int(11)  | YES  |     | NULL    |                |
+-------+----------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

 

语句1:SELECT [field1, field2 | *] into Table2 [IN externaldatabase] from Table1 where condition;

语句2:SELECT A.field1,B.field2 into C [IN externaldatabase] from A [inner | left | right] join B on [condition1] where condition2;

说明:[IN externaldatabase]可以实现跨数据库的数据复制。

注意:目标表(即Table2或C)不要存在,MySQL会自动创建,这是与INSERT INTO SELECT的一个很大的不同点。

 

示例:

mysql> SELECT * INTO Persons_backup FROM Persons;

 

mysql> SELECT *      //跨数据库的数据复制
    -> INTO Persons IN ‘Backup.mdb‘
    -> FROM Persons;

  

mysql> SELECT LastName,FirstName
    -> INTO Persons_backup
    -> FROM Persons;

  

mysql> SELECT LastName,Firstname
    -> INTO Persons_backup
    -> FROM Persons
    -> WHERE City=‘Beijing‘;

  

mysql> SELECT Persons.LastName,Orders.OrderNo  //表连接复制,即多表复制
    -> INTO Persons_Order_Backup
    -> FROM Persons
    -> INNER JOIN Orders
    -> ON Persons.Id_P=Orders.Id_P;

  

以上是关于MySQL复制表-SELECT INTO FROM的主要内容,如果未能解决你的问题,请参考以下文章

select into from和insert into select from两种表复制语句区别

oracle数据库表复制insert into select from跟create table as select * from 两种表复制语句区别

INSERT INTO MySQL 表 SELECT FROM PostgreSQL 表

select into from 和 insert into select

MySQL复制表-INSERT INTO SELECT

select into from 和 insert into select 的用法和区别