Tutorial on copying data from a data table to a new table in MySQL

  • 2020-12-20 03:49:02
  • OfStack

MySQL does not support SELECT... INTO grammar, using INSERT INTO... SELECT instead of the same usage, let's make a short answer here: 1. There are two situations in which the new table exists and does not exist, using different statements.
The new table does not exist
The replication table structure is the data to the new table


create table new_table
select * from old_talbe;

This method copies everything in old_table. It is important to note that new_table does not have primary key,Extra,auto_increment and other attributes in old_table, which need to be added manually. See the modified table below for details of field attributes.
Only the table structure is copied to the new table


#  The first 1 methods , Similar to that , Only the data is recorded null , That is to 1 a false conditions 
create table new_table
select * from old_table where 1=2;

#  The first 2 methods 
create table new_table like old_table;

2. New table exists
Copy the old table data to the new table (assuming two table structures 1)


insert into new_table
select * from old_table;

Copy the old table data to the new table (assuming that the two table structures are not identical)


insert into new_table(field1,field2,.....)
select field1,field2,field3 from old_table;

Copy all data


select * into new_table from old_table;

Only the table structure is copied to the new table


select * into new_talble from old_table where 1=2;

Example 3.

(1) There is no replication in the table


mysql>show tables; 
+-----------------+ 
|Tables_in_test1 | 
+-----------------+ 
|cpu_stat    | 
|test1      | 
|test2      | 
|test3      | 
+-----------------+ 
4rows in set (0.02 sec) 
 
mysql> create tabletest4 as select * from test1 where 1=0;  
// Only the table structure is copied  
QueryOK, 0 rows affected (0.06 sec) 
Records:0 Duplicates: 0 Warnings: 0 
 
mysql> create tabletest5 as select * from test1;  
// Put the table test1 All contents are copied as test5 
QueryOK, 7 rows affected (0.11 sec) 
Records:7 Duplicates: 0 Warnings: 0 


(2) The table has been replicated


mysql> create table test6(id int not null auto_increment primary key, name varchar(20)); 
Query OK, 0 rows affected (0.13 sec) 
 
mysql> insert into test6(name) select name from test1; 
// Only copy name column  
Query OK, 7 rows affected (0.06 sec) 
Records: 7 Duplicates: 0 Warnings: 0 
 
mysql> select * from test6; 
+----+-------+ 
| id | name | 
+----+-------+ 
| 1 | wu  | 
| 2 | terry | 
| 3 | tang | 
 ...  
7 rows in set (0.00 sec) 



Related articles: