| Subcribe via RSS

INSERT SELECT

May 27th, 2008 | No Comments | Posted in mysql by dreamluverz


I was trying to duplicate a record and the best solution I can find is to do it like this.

INSERT INTO table SELECT * FROM table WHERE {CONDITION}

But this is not a good idea if you have auto increment for your primary key so you can do it like this instead

INSERT INTO table (field1, field2, field3) SELECT field1, field2, field3 FROM table WHERE {CONDITION}

Take a closer look of the statement. At first I was trying to do it like the one shown below and I got an error column count doesn’t match. As you notice I specify the fields on SELECT and not on INSERT INTO.

INSERT INTO table SELECT field1, field2, field3 FROM table

Tags: , ,