INSERT INTO SELECT

Description

The INSERT INTO SELECT statement copies data from one table and inserts it into another table.

The existing records in the target table are unaffected.

Syntax

  1. INSERT INTO table2 (column1, column2, column3, ...)
  2. SELECT column1, column2, column3, ...
  3. FROM table1
  4. WHERE condition;

Examples

  1. create table t1(id int, name varchar(10));
  2. insert into t1 values(1, 'a');
  3. insert into t1 values(2, 'b');
  4. insert into t1 values(3, 'c');
  5. create table t2(id int, appname varchar(10), country varchar(10));
  6. insert into t2 values(1, 'appone', 'CN');
  7. insert into t2 values(2, 'apptwo', 'CN');
  8. INSERT INTO t1 (name) SELECT appname FROM t2;
  9. mysql> select * from t1;
  10. +------+--------+
  11. | id | name |
  12. +------+--------+
  13. | 1 | a |
  14. | 2 | b |
  15. | 3 | c |
  16. | NULL | appone |
  17. | NULL | apptwo |
  18. +------+--------+