爱情文章
当前位置:首页 > 爱情文章 > 列表页

mysql,复制表数据,表结构的3种方法_mysql这样复制表结构

泥巴往事网  发布于:2018-08-15  分类: 爱情文章 手机版

什么时候我们会用到复制表?例如:我现在对一张表进行操作,但是怕误删数据,所以在同一个数据库中建一个表结构一样,表数据也一样的表,以作备份。如果用mysqldump比较麻烦,备份.MYD,.MYI这样的文件呢,操作起来也还是麻烦。

一,复制表结构

方法1:

mysql> create table a like users; //复制表结构 Query OK, 0 rows affected (0.50 sec) mysql> show tables; +—————-+ | Tables_in_test | +—————-+ | a | | users | +—————-+ 2 rows in set (0.00 sec) mysql> create table a like users; //复制表结构 Query OK, 0 rows affected (0.50 sec) mysql> show tables; +----------------+ | Tables_in_test | +----------------+ | a | | users | +----------------+ 2 rows in set (0.00 sec)

方法2:

mysql> create table b select * from users limit 0; //复制表结构 Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> show tables; +—————-+ | Tables_in_test | +—————-+ | a | | b | | users | +—————-+ 3 rows in set (0.00 sec) mysql> create table b select * from users limit 0; //复制表结构 Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> show tables; +----------------+ | Tables_in_test | +----------------+ | a | | b | | users | +----------------+ 3 rows in set (0.00 sec)

方法3:

mysql> show create table usersG; //显示创表的sql *************************** 1. row *************************** Table: users Create Table: CREATE TABLE `users` ( //改表名 `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_name` varchar(60) NOT NULL DEFAULT ”, `user_pass` varchar(64) NOT NULL DEFAULT ”, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 //改auto_increment 1 row in set (0.00 sec) mysql> show create table usersG; //显示创表的sql *************************** 1. row *************************** Table: users Create Table: CREATE TABLE `users` ( //改表名 `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_name` varchar(60) NOT NULL DEFAULT "", `user_pass` varchar(64) NOT NULL DEFAULT "", PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 //改auto_increment 1 row in set (0.00 sec)

把sql语句copy出来,改一下表名和atuo_increment,然后在执行一下。

二,复制表数据,以及表结构

方法1:

mysql> create table c select * from users; //复制表的sql Query OK, 4 rows affected (0.00 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> create table c select * from users; //复制表的sql Query OK, 4 rows affected (0.00 sec) Records: 4 Duplicates: 0 Warnings: 0

方法2:

mysql> create table d select user_name,user_pass from users where id=1; Query OK, 1 row affected (0.00 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> create table d select user_name,user_pass from users where id=1; Query OK, 1 row affected (0.00 sec) Records: 1 Duplicates: 0 Warnings: 0

上面的2种方法,方便,快捷,灵活性强。

方法3:

先创建一个空表, INSERT INTO 新表 SELECT * FROM 旧表 ,或者

INSERT INTO 新表(字段1,字段2,…….) SELECT 字段1,字段2,…… FROM 旧表

这种方法不是很方便,也是我以前经常用的。

本文已影响

mysql,复制表数据,表结构的3种方法_mysql这样复制表结构