1.新表不存在
create table new_table select * from old_talbe;
這種方法會將old_table中所有的內容都拷貝過來,用這種方法需要注意,new_table中沒有了old_table中的primary key,Extra,auto_increment等屬性,需要自己手動加,具體參看后面的修改表即字段屬性.
只復制表結構到新表
# 第一種方法,和上面類似,只是數據記錄為空,即給一個false條件 create table new_table select * from old_table where 1=2; # 第二種方法 create table new_table like old_table;
2.新表存在
復制舊表數據到新表(假設兩個表結構一樣)
insert into new_table select * 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;
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 條件不成立時,只復制表結構,沒有任務數據
1 mysql
create table t2 as select c1 from t1; --正確,一般用法 --新表中對列重命名 create table t2 as select c1 c2 from t1; --正確 create table t2(c2 varchar(50)) as select c1 from t1; --語法正確,但不是預期結果 desc t2; --c1, c2 create table t2(c2) as select c1 from t1; --錯誤 ---------------------
2 oracle
create table t2 as select c1 from t1; --正確,一般用法 --新表中對列重命名 create table t2 as select c1 c2 from t1; --正確 create table t2(c2) as select c1 from t1; --正確 desc t2; --c2 create table t1(col1 varchar(255)) as select c1 from t1; --錯誤,不能指定數據類型