CREATE TABLE 表名 AS SELECT 語句


 

1.新表不存在
復制表結構即數據到新表

?
1
2
create table new_table
select * from old_talbe;

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

?
1
2
3
4
5
6
# 第一種方法,和上面類似,只是數據記錄為空,即給一個 false 條件
create table new_table
select * from old_table where 1=2;
 
# 第二種方法
create table new_table like old_table;

2.新表存在
復制舊表數據到新表(假設兩個表結構一樣)

?
1
2
insert into new_table
select * from old_table;

復制舊表數據到新表(假設兩個表結構不一樣)

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

復制全部數據

?
1
select * into new_table from old_table;

只復制表結構到新表

?
1
select * into new_talble from old_table where 1=2;

 create table a like b;

create table c_relation as select c.memberId,m.merchantId,memb.phone from c_merchant as m inner join c_customer c on c.userId=m.userId inner join c_member memb on memb.id=c.memberId where memb.status=10;

 

由上面的使用 CREATE TABLE 表名 AS SELECT 語句可以看出:

    1:只會復制表數據和表結構,不會有任何約束。

    2:當 where 條件不成立時,只復制表結構,沒有任務數據。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM