mysql如何把一个表直接拷贝到一个新的表澳门新浦
一:在新表已经建立好的情况下
0、复制表结构及数据到新表
CREATE TABLE 新表 SELECT * FROM 旧表
这种方法会将oldtable中所有的内容都拷贝过来,当然我们可以用delete from
newtable;来删除。
不过这种方法的一个最不好的地方就是新表中没有了旧表的primary
key、Extra(auto_increment)等属性。需要自己用"alter"添加,而且容易搞错。
1,拷贝所有的字段
insert into new_table select * from old_table
2,拷贝部分字段表
insert into new_table(id,name,sex) select id,name,sex from old_table
3,拷贝部分的行
insert into new_table select * from old_table where id="1"
4,拷贝部分的行和字段
1、只复制表结构到新表
CREATE TABLE 新表 SELECT * FROM 旧表 WHERE 1=2
或CREATE TABLE 新表 LIKE 旧表
insert into new_table(id,name,sex) select id,name,sex form old_table where id='1'
create table score_youxiu select * from score where grade >90;
二:在新表还没有建的情况下
//复制表的部分内容
方案一:
create table score_youxiu select * from score where id%4=0;
create table new_table (select * from old_table)
//应用:分表办法(按业务需要,取模(id%4),取偏移量)
这种方案建的话,只是拷贝的查询的结果,新表不会有主键和索引
方案二:
create table new_table LIKE old_table
该方案只能拷贝表结构到新表中,不会拷贝数据
方案三:
如果要真正的复制一个数据到新表,我们可以直接执行下面的语句
2、复制旧表的数据到新表(假设两个表结构一样)
INSERT INTO 新表 SELECT * FROM 旧表
create table new_table LIKE old_table;
insert into new_table select * from old_table;
三:我们也可以操作其它的数据库中的表
create table new_table LIKE ortherdatabase.old_table;
insert into new_table select * from ortherdatabase.old_table;
ortherdatabase.old_table中的ortherdatabase是指定的数据库名
3、复制旧表的数据到新表(假设两个表结构不一样)
INSERT INTO 新表(字段1,字段2,.......) SELECT 字段1,字段2,...... FROM
旧表
四:我们也可以在新建表时改名字
insert into ss (id,stu_id) select id,stu_id from score;
create table new_table (select id,name as username from old_table)
insert into score3 (id,stu_id,c_name) select id,stu_id,c_name from score;