Three methods of mysql copying table data and table structure

1, Copy table structure

Method 1:

  1. mysql> create table a like users;         //Copy table structure  
  2. Query OK, 0 rows affected (0.50 sec)  
  3.   
  4. mysql> show tables;  
  5. +----------------+  
  6. | Tables_in_test |  
  7. +----------------+  
  8. | a              |  
  9. | users          |  
  10. +----------------+  
  11. 2 rows in set (0.00 sec)  

Method 2:

  1. mysql> create table b select * from users limit 0;   //Copy table structure  
  2. Query OK, 0 rows affected (0.00 sec)  
  3. Records: 0  Duplicates: 0  Warnings: 0  
  4.   
  5. mysql> show tables;  
  6. +----------------+  
  7. | Tables_in_test |  
  8. +----------------+  
  9. | a              |  
  10. | b              |  
  11. | users          |  
  12. +----------------+  
  13. 3 rows in set (0.00 sec)  

Method 3:

  1. mysql> show create table users\G;          //Display the created sql  
  2. *************************** 1. row ***************************  
  3.  Table: users  
  4. Create Table: CREATE TABLE `users` (       //Change table name  
  5.  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  6.  `user_name` varchar(60) NOT NULL DEFAULT '',  
  7.  `user_pass` varchar(64) NOT NULL DEFAULT '',  
  8.  PRIMARY KEY (`ID`)  
  9. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8  //Change auto increment  
  10. 1 row in set (0.00 sec)  

copy the sql statement, change the table name and atuo increment, and then execute it.

2, Copy table data and table structure

Method 1:

  1. mysql> create table c select * from users;      //sql of replication table  
  2. Query OK, 4 rows affected (0.00 sec)  
  3. Records: 4  Duplicates: 0  Warnings: 0  

Method 2:

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

The above two methods are convenient, fast and flexible.

Method 3:

First create an empty table, INSERT INTO new table SELECT * FROM old table, or

INSERT INTO new table (field 1, field 2 .) SELECT field 1, field 2 FROM old table

This method is not very convenient, which I used to use.

Keywords: MySQL SQL

Added by Dj_Lord on Sun, 03 May 2020 04:02:36 +0300