標籤:val 資料 rom 複製表 建立 mys style dup ted
基礎table為:
mysql> select * from staff;+----+----------+-------+| id | name | slary |+----+----------+-------+| 3 | haofugui | 10000 || 4 | guoming | 3500 || 5 | haotian | 2900 |+----+----------+-------+3 rows in set (0.00 sec)mysql> describe staff;+-------+----------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-------+----------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || name | char(20) | YES | | NULL | || slary | int(11) | YES | | NULL | |+-------+----------+------+-----+---------+----------------+3 rows in set (0.00 sec)
INSERT INTO SELECT 語句從一個表複製資料,然後把資料插入到一個已存在的表(目標表)中,目標表中任何已存在的行都不會受影響。
語句1:Insert into Table2(field1,field2,…) select value1,value2,… from Table1 where condition;
語句2:Insert into Table2 select * from Table1;
說明:1)目標表Table2必須存在,MySQL不會自動建立;
2)語句1一般用於兩個表結構一致的情況,而語句2用於表結構不一致的情況;
3)語句1中涉及的field1,field2也必須存在;
4)若Table2有主鍵且不具備自動成長,則 field1, field2…中必須包括主鍵。
樣本:
mysql> create table staff_bak_1 like staff;Query OK, 0 rows affected (0.05 sec)mysql> describe staff_bak_1;+-------+----------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-------+----------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || name | char(20) | YES | | NULL | || slary | int(11) | YES | | NULL | |+-------+----------+------+-----+---------+----------------+3 rows in set (0.01 sec)mysql> select * from staff_bak_1;Empty set (0.00 sec)mysql> insert into staff_bak_1 select * from staff;Query OK, 3 rows affected (0.00 sec)Records: 3 Duplicates: 0 Warnings: 0mysql> select * from staff_bak_1;+----+----------+-------+| id | name | slary |+----+----------+-------+| 3 | haofugui | 10000 || 4 | guoming | 3500 || 5 | haotian | 2900 |+----+----------+-------+3 rows in set (0.00 sec)
mysql> create table staff_bak_2 -> (id int auto_increment primary key, -> name char(20));Query OK, 0 rows affected (0.05 sec)mysql> describe staff_bak_2;+-------+----------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-------+----------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || name | char(20) | YES | | NULL | |+-------+----------+------+-----+---------+----------------+2 rows in set (0.01 sec)mysql> insert into staff_bak_2(name) select name from staff where id!=5;Query OK, 2 rows affected (0.00 sec)Records: 2 Duplicates: 0 Warnings: 0mysql> select * from staff_bak_2;+----+----------+| id | name |+----+----------+| 1 | haofugui || 2 | guoming |+----+----------+2 rows in set (0.00 sec)
MySQL複製表-INSERT INTO SELECT