insert into table from a second table

By | 4 December, 2008

Its simple but i thought of leaving it here if i forget (which is usually the case) how to do it again.

If you want to insert the records from tableA into tableB, you do something like this:

INSERT INTO tableA SELECT * FROM tableB

You have to make sure all fields are the same on both tables or you will get an error.

You can list the fields so you wont go wrong:

INSERT INTO tableA(name,address) SELECT name,address FROM tableB

And you can even prevent the key field from being the same:

INSERT INTO tableA SELECT * FROM tableB ON DUPLICATE KEY UPDATE tableB.state =”changed”

Like i mentioned, simple.