MySQL 复制表
复制表结构与数据:CREATE TABLE ... LIKE / AS。
Key PointsLIKE 复制结构(含索引),AS 复制数据(可能丢索引)。
两种复制
SQL
-- 只复制结构(含索引、自增),不含数据
CREATE TABLE users_bak LIKE users;
-- 复制结构 + 数据(但索引/默认值可能丢失)
CREATE TABLE users_snap AS SELECT * FROM users;Output
Query OK, 0 rows affected (0.04 sec)
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0For a real backup use
CREATE TABLE ... LIKE then INSERT INTO ... SELECT to keep indexes and constraints; AS SELECT drops them.两种复制
SQL
-- 只复制结构(含索引、自增),不含数据
CREATE TABLE users_bak LIKE users;
-- 复制结构 + 数据(但索引/默认值可能丢失)
CREATE TABLE users_snap AS SELECT * FROM users;Output
Query OK, 0 rows affected (0.04 sec)
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0做表备份用
CREATE TABLE ... LIKE + INSERT INTO ... SELECT,能保住索引与约束;AS SELECT 得到的是普通表,自增和索引都得重新加。