views:

71

answers:

4

I new to MySQL. I would like to copy the content of one table to another table within the same database. Basically, I would like to insert to a table from another table. Is there easy way of doing this?

thanks for any help

+9  A: 

INSERT INTO TARGET_TABLE SELECT * FROM SOURCE_TABLE

EDIT: or if the tables have different structures you can also:

INSERT INTO TARGET_TABLE (col1,col2) SELECT col1,col2 FROM SOURCE_TABLE

ggiroux
wow...that is simple
Joneph O.
+3  A: 

If the table doesn't exist, you can create one with the same schema like so:

CREATE TABLE table2 LIKE table1;

Then, to copy the data over:

INSERT INTO table2 SELECT * FROM table1
GSto
+1 for the create LIKE tip :)
Alex
+1  A: 

If table1 is large and you don't want to lock it for the duration of the copy process, you can do a dump-and-load instead:

CREATE TABLE table2 LIKE table1;

SELECT * INTO OUTFILE '/tmp/table1.txt' FROM table1;
LOAD DATA INFILE '/tmp/table1.txt' INTO TABLE table2;
Ike Walker
+1 for the outfile shenanigans
Martin
+1  A: 

If you want to create and copy the content in a single shot, just use the SELECT:

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

Frank Heikens
+1 - although the new table won't have the index definitions from the first. The "create ... like ..." approach will copy index definitions too.
Martin