MySQL中複製資料表中的資料到新表中的操作教程_Mysql

來源:互聯網
上載者:User

MySQL是不支援SELECT … INTO文法的,使用INSERT INTO … SELECT替代相同用法,下面我們我們這裡簡答分一下新表存在和不存在兩種情況,具體使用不同的語句。
1.新表不存在
複製表結構即資料到新表

create table new_tableselect * from old_talbe;

這種方法會將old_table中所有的內容都拷貝過來,用這種方法需要注意,new_table中沒有了old_table中的primary key,Extra,auto_increment等屬性,需要自己手動加,具體參看後面的修改表即欄位屬性.
只複製表結構到新表

# 第一種方法,和上面類似,只是資料記錄為空白,即給一個false條件create table new_tableselect * from old_table where 1=2;# 第二種方法create table new_table like old_table;

2.新表存在
複製舊錶資料到新表(假設兩個表結構一樣)

insert into new_tableselect * from old_table;

複製舊錶資料到新表(假設兩個表結構不一樣)

insert into new_table(field1,field2,.....)select field1,field2,field3 from old_table;

複製全部資料

select * into new_table from old_table;

只複製表結構到新表

select * into new_talble from old_table where 1=2;

3.執行個體

(1)表不存在複製

mysql>show tables; +-----------------+ |Tables_in_test1 | +-----------------+ |cpu_stat    | |test1      | |test2      | |test3      | +-----------------+ 4rows in set (0.02 sec)  mysql> create tabletest4 as select * from test1 where 1=0;  //僅複製表結構 QueryOK, 0 rows affected (0.06 sec) Records:0 Duplicates: 0 Warnings: 0  mysql> create tabletest5 as select * from test1;  //把表test1所有內容複寫為test5 QueryOK, 7 rows affected (0.11 sec) Records:7 Duplicates: 0 Warnings: 0 

 
(2)表已經存在複製

mysql> create table test6(id int not null auto_increment primary key, name varchar(20)); Query OK, 0 rows affected (0.13 sec)  mysql> insert into test6(name) select name from test1; //只複製name列 Query OK, 7 rows affected (0.06 sec) Records: 7 Duplicates: 0 Warnings: 0  mysql> select * from test6; +----+-------+ | id | name | +----+-------+ | 1 | wu  | | 2 | terry | | 3 | tang | …… 7 rows in set (0.00 sec) 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.