Skip to content

MySQL复制表

概述

创建现有表的副本对于备份、测试或数据迁移很有用。MySQL提供了多种复制表的方法,包括仅结构、仅数据或两者都复制。

复制方法

CREATE TABLE AS:从SELECT查询创建 CREATE TABLE LIKE:仅复制结构 INSERT SELECT:复制数据到现有表 import / mysqldump:完整表导出/导入

CREATE TABLE AS / CREATE TABLE AS

复制结构和数据

sql
-- Copy entire table

-- Copy with WHERE clause

-- Copy specific columns

-- Copy with expressions

复制并添加新列

sql
-- Copy and add calculated column

CREATE TABLE LIKE / CREATE TABLE LIKE

仅复制结构

sql
-- Copy structure without data

-- Verify structure
-- Has same columns, types, indexes as users

-- Add data later

复制并指定选项

sql
-- Copy structure and modify

INSERT SELECT / INSERT SELECT

复制数据到现有表

sql
-- Create empty table with same structure

-- Copy data

-- Copy with transformation

批量复制

sql
-- Copy multiple tables

-- Copy with conditions

完整复制工作流

步骤1:创建结构

sql
-- Method 1: LIKE (exact structure copy)

-- Method 2: CREATE TABLE (customize structure)

步骤2:复制数据

sql
-- Copy all data

-- Copy with filter

-- Copy with transformation

步骤3:验证

sql
-- Compare row counts

-- Compare data samples

使用mysqldump复制

导出表

bash
# Export single table

# Export with data only

# Export with structure only

# Export with specific conditions

导入表

bash
# Import to new table

# Import to different database

# Import with table rename

跨数据库复制

复制到另一个数据库

sql
-- Method 1: CREATE TABLE AS

-- Method 2: Cross-database INSERT

使用mysqldump跨库复制

bash
# Export from source database

# Import to target database

# Or single command

带约束复制

带主键复制

sql
-- Copy and reset auto increment

-- Insert with new IDs

带外键复制

sql
-- Copy parent and child tables

-- Copy data

-- Re-add foreign key to backup

复制性能

优化大表复制

sql
-- Method 1: Use CREATE TABLE AS with LIMIT

-- Continue in batches

-- Method 2: Disable indexes during copy

-- Method 3: Use LOAD DATA INFILE
-- Export to CSV

-- Import to new table

监控复制进度

sql
-- Check progress with row counts

-- Calculate percentage

复制场景

场景1:更改前备份

sql
-- Create backup before major changes

-- Perform changes

-- Rollback if needed

场景2:归档旧数据

sql
-- Create archive table

-- Move old orders

-- Delete from main table

场景3:创建测试环境

sql
-- Create test database

-- Copy production tables

-- Anonymize sensitive data

场景4:数据迁移

sql
-- Create new schema tables

-- Migrate data with transformations

-- Verify migration

mysqldump高级复制

部分表复制

bash
# Export specific columns
    --skip-add-locks database_name table_name \
    --where="id BETWEEN 1 AND 1000" > partial_data.sql

# Export with row limit

复制到不同服务器

bash
# Export from source

# Import to target

# Or single command

小结

MySQL中复制表提供:

备份:为安全创建副本 testing / 测试:为开发/测试克隆 迁移:在模式间移动数据 归档:将旧数据移动到归档 多种方法:CREATE TABLE AS、LIKE、mysqldump

根据需要选择适当的方法:完整复制、仅结构或带转换的仅数据。


上一个:临时表

下一个:元数据