將查詢結果插入到表中
阿新 • • 發佈:2017-06-14
not 創建 lis default inf pre police span signed
語法:INSERT INTO table_name1 (column_list) SELECT (column_list2) FROM table_name2 WHERE (condition);
以下創建 person 和 person_old 兩個表,將 person_old 的查詢結果然後插入到 person 表中
mysql> CREATE TABLE person # 創建 person 表 -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT, -> name CHAR(40) NOT NULL DEFAULT ‘‘, -> age INT NOT NULL DEFAULT 0, -> info CHAR(50) NULL, -> PRIMARY KEY (id) -> );
mysql> CREATE TABLE person_old # 創建 person_old 表 -> ( -> id INT UNSIGNED NOT NULL NULL AUTO_INCREMENT, -> name CHAR(40) NOT NULL DEFAULT ‘‘, -> age INT NOT NULL DEFAULT 0, -> info CHAR(50) NULL, -> PRIMARY KEY (id) -> );
mysql> INSERT INTO person_old VALUES (1, ‘Harry‘, 20, ‘student‘), (2, ‘Beckham‘, 31, ‘police‘); # 在 person_old 表中插入兩條數據
mysql> INSERT INTO person(id, name, age, info) SELECT id, name, age, info FROM person_old; # 將 person_old 的查詢結果然後插入到 person 表中
mysql> SELECT * FROM person; # 查詢 person 表是否有插入數據
+----+---------+-----+------------+
| id | name | age | info |
+----+---------+-----+------------+
| 1 | Harry | 20 | student |
| 2 | Beckham | 31 | police |
+----+---------+-----+------------+
將查詢結果插入到表中