在mysql數據庫開發中,我們有時候需要復制或拷貝一張表結構和數據到例外一張表,這個時候我們可以使用create ... select ... from語句來實現,本文章向大家介紹mysql復制表結構和數據一個簡單實例,
比如現在有一張表,我們要將該表復制一份,以備以後使用,那麼如何使用mysql語句來實現呢?其實我們可以直接使用create ... select ... from語句來實現,具體實現方法請看下面實例。
我們先來創建一張Topic表,創建Topic表的SQL語句如下:
mysql> CREATE TABLE Topic( -> TopicID SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name VARCHAR(50) NOT NULL, -> InStock SMALLINT UNSIGNED NOT NULL, -> OnOrder SMALLINT UNSIGNED NOT NULL, -> Reserved SMALLINT UNSIGNED NOT NULL, -> Department ENUM('Classical', 'Popular') NOT NULL, -> Category VARCHAR(20) NOT NULL, -> RowUpdate TIMESTAMP NOT NULL -> );
向Topic表中插入數據:
mysql> INSERT INTO Topic (Name, InStock, OnOrder, Reserved, Department, Category) VALUES -> ('Java', 10, 5, 3, 'Popular', 'Rock'), -> ('JavaScript', 10, 5, 3, 'Classical', 'Opera'), -> ('C Sharp', 17, 4, 1, 'Popular', 'Jazz'), -> ('C', 9, 4, 2, 'Classical', 'Dance'), -> ('C++', 24, 2, 5, 'Classical', 'General'), -> ('Perl', 16, 6, 8, 'Classical', 'Vocal'), -> ('Python', 2, 25, 6, 'Popular', 'Blues'), -> ('Php', 32, 3, 10, 'Popular', 'Jazz'), -> ('ASP.net', 12, 15, 13, 'Popular', 'Country'), -> ('VB.net', 5, 20, 10, 'Popular', 'New Age'), -> ('VC.net', 24, 11, 14, 'Popular', 'New Age'), -> ('UML', 42, 17, 17, 'Classical', 'General'), -> ('www.java2s.com',25, 44, 28, 'Classical', 'Dance'), -> ('Oracle', 32, 15, 12, 'Classical', 'General'), -> ('Pl/SQL', 20, 10, 5, 'Classical', 'Opera'), -> ('Sql Server', 23, 12, 8, 'Classical', 'General'); Query OK, 16 rows affected (0.00 sec) Records: 16 Duplicates: 0 Warnings: 0
現在我們要將這張表復制一份,具體操作如下:
mysql> CREATE TABLE Topic2 -> ( -> TopicID SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name VARCHAR(50) NOT NULL, -> InStock SMALLINT UNSIGNED NOT NULL, -> OnOrder SMALLINT UNSIGNED NOT NULL, -> Reserved SMALLINT UNSIGNED NOT NULL, -> Department ENUM('Classical', 'Popular') NOT NULL, -> Category VARCHAR(20) NOT NULL, -> RowUpdate TIMESTAMP NOT NULL -> ) -> SELECT * -> FROM Topic
這樣表Topic2和Topic表不僅擁有相同的表結構,表數據也是一樣的了。
例外,如果我們只需要復制表結構,不需要復制數據,也可以使用create like來實現:
create table a like users;
感謝閱讀此文,希望能幫助到大家,謝謝大家對本站的支持!