Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql: Copy table structure including foreign keys

Tags:

I know how to copy a table using create new_table like old_table, but that does not copy over the foreign key constraints as well. I can also do string manipulation on the result from show create table old_table (using regular expressions to replace the table name and the foreign key constraint names), but that seems error prone. Is there a better way to copy the structure of a table, including the foreign keys?

like image 373
nicholas a. evans Avatar asked Sep 20 '10 21:09

nicholas a. evans


People also ask

How do you copy a table structure?

Right-click the table you want to copy in Database Explorer and select Duplicate Object. In the dialog that opens, select the destination db. Select to copy the table data or structure only. Specify the name of the new table, and click OK.

How do I copy a table from one schema to another in MySQL?

1) Use the ALTER TABLE ... RENAME command and parameter to move the table to the target schema. 2) Use the CREATE TABLE ... CLONE command and parameter to clone the table in the target schema.


1 Answers

Possibly you could write a procedure that after the create table like prepares ALTER TABLE ... statements, based on information from:

SELECT *  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE  WHERE TABLE_NAME LIKE '<table_name>'  AND TABLE_SCHEMA = '<db_name>' AND REFERENCED_TABLE_NAME IS NOT NULL; 
like image 83
Wrikken Avatar answered Sep 25 '22 16:09

Wrikken