如何克隆/复制表格及其中包含的数据、触发器和索引?
为了创建一个新的表格,它与旧表格的结构、数据、触发器和索引完全一样,我们需要运行以下两个查询。
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));
Query OK, 0 rows affected (0.21 sec)
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');
Query OK, 2 rows affected (0.07 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> Select * from employee;
+----+--------+
| ID | NAME |
+----+--------+
| 1 | Gaurav |
| 2 | Raman |
+----+--------+
2 rows in set (0.00 sec)以下查询将创建一个表格 employee1,它的结构与表格 employee 相似。可以通过运行 DESCRIBE 查询来检查它。
mysql> create table employee1 like employee; Query OK, 0 rows affected (0.19 sec) 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; Query OK, 2 rows affected (0.09 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from employee1; +----+--------+ | ID | NAME | +----+--------+ | 1 | Gaurav | | 2 | Raman | +----+--------+ 2 rows in set (0.00 sec)
通过这种方法,我们可以克隆该表格及其数据、触发器和索引。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP