MySQL复制表结构、表数据的方法

1、复制表结构及数据到新表

create table new_table_name select * from old_table_name;

这种方法的一个最不好的地方就是新表中没有了旧表的primary key、Extra(auto_increment)等属性。

2、只复制表结构到新表

create table new_table_name select * from old_table_name where 1=2;

create table new_table_name like old_table_name;

3、复制旧表的数据到新表(假设两个表结构一样)

insert into new_table_name select * from old_table_name;

4、复制旧表的数据到新表(假设两个表结构不一样)

insert into new_table_name(字段1,字段2,字段3) select (字段1,字段2,字段3) from old_table_name;

5、表不在同一数据库中(如:db1 table1,db2 table2)

完全复制

insert into db1.table1 select * from db2.table2;

不复制重复记录

insert into db1.table1 select distinct* from db2.table2;

复制前10条记录

insert into db1.table1 select 10* from db2.table2;

6、查看表的创建SQL

show create table table_name;

这样会将表的创建SQL列出。我们只需要将该SQL拷贝出来,更改table_name,就可以创建一个完全一样的表。

7、清除表数据

delete from table_name;

truncate table table_name;

不带where参数的delete语句可以删除mysql表中所有内容;
使用truncate table也可以清空mysql表中所有内容。

但是使用delete清空表中的记录,内容的ID仍然从删除点的ID继续建立,而不是从1开始。

而truncate相当于保留了表的结构而重新建立了一张同样的新表。

效率上truncate比delete快。

但truncate删除后不记录mysql日志,不可以恢复数据。

delete的效果有点像将mysql表中所有记录一条一条删除到删完。

猜你喜欢

转载自blog.csdn.net/weixin_56175092/article/details/120509499