12

How to duplicate a table with keys & other structure features retained? including primary key, foreign keys, and indexes.

Can this be done with a single MySQL query?

I'm using "create table newtable as select..." but this method makes all keys & indexes lost.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jondinham
  • 8,271
  • 17
  • 80
  • 137
  • 1
    You can turn indexes on after creating table using "ALTER TABLE ADD INDEX ...". This way is good, because insertion in new table will be faster without indexes. – Oroboros102 Nov 22 '11 at 12:23
  • possible duplicate of [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – mimarcel Mar 06 '14 at 12:48

3 Answers3

30

duplicating a table from another table (with indexing and structure)cannot be done with a single query you will need need 2 queries.

1) To create Duplicate table.

CREATE TABLE Table2 LIKE Table1;

This will create an exact copy of the table.

2) Fill in the Duplicate table with values from original table.

INSERT INTO Table2 SELECT * from Table1;

will fill Table2 with all the records fom Table1

RRikesh
  • 14,112
  • 5
  • 49
  • 70
Shirish11
  • 1,587
  • 5
  • 17
  • 39
7

you can do it in this query

CREATE TABLE a LIKE b

after you can insert

INSERT INTO a SELECT * FROM b

read more information in this article

Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
0

Following query creates and duplicates data.

CREATE TABLE table2 SELECT * FROM table1

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71