如何克隆/复制表及其数据,触发器和索引?

为了创建与旧表一样的新表及其数据,触发器和索引,我们需要运行以下两个查询

CREATE TABLE new_table LIKE old_table;
INSERT new_table SELECT * from old_table;

示例

mysql> Create table employee(ID INT PRIMARY KEY NOT NULL AUTO_INCREMENT, NAME VARCHAR(20));

mysql> Describe employee;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| ID    | int(11)     | NO   | PRI | NULL    | auto_increment |
| NAME  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.07 sec)

mysql> Insert into employee(name) values('Gaurav'),('Raman');
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from employee;
+----+--------+
| ID | NAME   |
+----+--------+
| 1  | Gaurav |
| 2  | Raman  |
+----+--------+
2 rows in set (0.00 sec)

下面的查询将创建与表employee具有相似结构的表employee1。可以通过运行DESCRIBE查询来检查它。

mysql> create table employee1 like employee;

mysql> describe employee1;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| ID    | int(11)     | NO   | PRI | NULL    | auto_increment |
| NAME  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.14 sec)

现在,下面的查询将在employee1中插入与employee中相同的值,可以按以下方式检查

mysql> INSERT INTO employee1 select * from employee;
Records: 2 Duplicates: 0 Warnings: 0

mysql> select * from employee1;
+----+--------+
| ID | NAME   |
+----+--------+
| 1  | Gaurav |
| 2  | Raman  |
+----+--------+
2 rows in set (0.00 sec)

这样,我们也可以将表及其数据,触发器和索引一起克隆。

猜你喜欢