SoFunction
Updated on 2025-03-01

5 ways to copy table structure and data in MySQL

Copying the table structure and its data in MySQL can be implemented in a variety of ways. Here are some commonly used methods:

1. Use CREATE TABLE ... LIKE and INSERT INTO ... SELECT

This method can quickly copy table structure and data.

Copy the table structure

CREATE TABLE new_table LIKE old_table;

Copy table data

INSERT INTO new_table
SELECT * FROM old_table;

2. Use CREATE TABLE... AS SELECT

This method can create tables and fill data directly in a statement.

CREATE TABLE new_table AS SELECT * FROM old_table;

3. Use mysqldump

If you need to copy the table structure and data across servers, or back up and restore the entire database, you can usemysqldumptool.

Export table structure and data

mysqldump -u username -p database_name table_name > 

Import table structure and data

mysql -u username -p database_name < 

4. Use INSERT ... SELECT (suitable for different table names)

If you need to copy data from one table to another, but the table name is different, you can useINSERT ... SELECTSentence.

INSERT INTO new_table
SELECT * FROM old_table;

5. Use CREATE TABLE... SELECT

If you need to create a new table and copy the data at the same time, you can useCREATE TABLE ... SELECTSentence.

CREATE TABLE new_table AS SELECT * FROM old_table;

Example

Suppose you have a name calledjobsthe table you want to copy its structure and data to a table calledjobs_backupin the new table.

Copy the table structure

CREATE TABLE jobs_backup LIKE jobs;

Copy table data

INSERT INTO jobs_backup
SELECT * FROM jobs;

Or, you can useCREATE TABLE ... AS SELECTComplete these two operations at once:

CREATE TABLE jobs_backup AS SELECT * FROM jobs;

Things to note

  • Make sure the target table does not exist, or delete it before copying to avoid conflicts.
  • If the table is large, consider using batch inserts or transactions to improve efficiency.
  • If there are foreign keys or other constraints in the table, make sure that these constraints are handled correctly during the replication process.

This is the end of this article about 5 ways to copy table structure and data in MySQL. For more related content on MySQL replication table structure, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!