如何克隆/複製表格及其中包含的資料、觸發器和索引?
為了建立一個新的表格,它與舊錶格的結構、資料、觸發器和索引完全一樣,我們需要執行以下兩個查詢。
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