Search the MySQL manual:
MySQL Manual

Buy this Reference Manual in softcover from Barnes & Noble!

/ / Up / Table of Contents

6.4.3.1 Синтаксис оператора INSERT ... SELECT

INSERT [LOW_PRIORITY] [IGNORE] [INTO] tbl_name [(column list)] SELECT ...

Команда INSERT ... SELECT обеспечивает возможность быстрого внесения большого количества строк в таблицу из одной или более таблиц.

INSERT INTO tblTemp2 (fldID) SELECT tblTemp1.fldOrder_ID 
        FROM tblTemp1
        WHERE tblTemp1.fldOrder_ID > 100;

Для команды INSERT ... SELECT необходимо соблюдение следующих условий:

Разумеется, для перезаписи старых строк можно вместо INSERT использовать REPLACE.

User Comments

Posted by Bill Rogers on Wednesday July 3 2002, @4:21pm [Delete] [Edit]

The fields have to be in the same order. If the
existing table has fields B, C, A, and the table being
append has fields A, B, C, the data in A goes into the
B field, B goes into the C field, and C goes into the A
field.

Posted by Ken Weide on Friday September 13 2002, @6:42am [Delete] [Edit]

As a workaround for sub select or views, I have
found 'create table' useful:
drop table temp; create temporary table temp
select * from testtable;

OR use the 'IN' syntax ref.: 1.7.4.1 SubSELECTs

Posted by Howard Brown on Monday December 9 2002, @3:28pm [Delete] [Edit]

It seems INSERT_SELECT has issues with field type
DATE.

Attempting to use the INSERT_SELECT construct
yields corrupted dates. For example, 2002-12-09
becomes 2012-09-02.

Posted by Jose K.K on Tuesday February 4 2003, @11:06pm [Delete] [Edit]

Select from two table will not work.

The insert_select will not work, if selecting specific values with specific conditions using select.

Posted by on Saturday March 1 2003, @6:20am [Delete] [Edit]

insert into A select '0', Ab.date, 1 from A as Ab where Ab.log = 'Z';
will not work under mysql !

Posted by on Friday March 7 2003, @7:08pm [Delete] [Edit]

Your auto_increment field will be an issue.

The trick is, if you want your auto_increment to work, you have to leave it out in the grammar:

ccl.ccl_maintest.id is an int(10), auto_increment, PRIMARY and Next_AutoIndex = 52

This worked (I don't include "id"):

INSERT INTO ccl.ccl_maintest( YR, AU, ST, SD, SC ) SELECT YR, AU, ST, SD, SC FROM jdaxell.ccl WHERE id = 24

It inserted jdaxell.ccl.id=24 correctly into ccl.ccl_maintest where ccl.ccl_maintest.id = 53.

This did not work (I include "id"):

INSERT INTO ccl.ccl_maintest( id, YR, AU, ST, SD, SC ) SELECT id, YR, AU, ST, SD, SC FROM jdaxell.ccl WHERE id = 24

In my second example, it copied from jdaxell.ccl.id=24 and inserts at ccl.ccl_maintest.id=24. Auto_Increment on the auto_incremented field "id" will not work if you declare it in the insert & select statements.

Likewise this code is useless, "if" you want auto_increment to work.

insert into ccl.ccl_maintest (*) select * FROM jdaxell.ccl WHERE id = 24

Add your own comment.

Top / / / Up / Table of Contents