views:

329

answers:

2

I searched for this here and on google and surprisingly couldn't find an answer. I tried to create syntax to submit to mysql that would create multiple tables with the same columns, but it returned an error. Can you point out what is wrong with my syntax, or if this is even possible?

 CREATE TABLE news, life
 (
 id int PRIMARY KEY AUTO_INCREMENT ,
 name varchar( 30 ) ,
 email varchar( 50 ) ,
 COMMENT text,
 datetime datetime,
 ip varchar( 20 )
 ) 
+2  A: 

It's not possible like that.

Think about your table design. This sounds like you should consider creating a single table and adding another column type that will be news or life (or a reference to another table defining types).


If you really need two tables, create your first table:

 CREATE TABLE news
 (
 id int PRIMARY KEY AUTO_INCREMENT ,
 name varchar( 30 ) ,
 email varchar( 50 ) ,
 COMMENT text,
 datetime datetime,
 ip varchar( 20 )
 )

and then

CREATE TABLE life AS ( SELECT * FROM news where 1=2 );

Indexes and constraints (UNIQUE, PRIMARY KEY, FOREIGN KEY) will not be copied though. You will have to handle them yourself.

Peter Lang
peter,thanks for your response. appreciate the concern about the table design, it is actually much more complex than that, i was just using a small example. can you explain where 1=2? would that code change if i'm creating more than 2 tables?
Dave Kiss
Still not sure why you need more than one table... Using `1=2` makes sure that no rows are returned (this would actually copy content of `news` to `life` otherwise). Code will be the same when creating more than one table. See my edit about indexes and constraints.
Peter Lang
+2  A: 

you are in mysql so you can use the LIKE clause of the CREATE TABLE command; that way you will also get column attributes and indexes copied over e.g.

CREATE TABLE new_tbl LIKE orig_tbl;

see http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table: CREATE TABLE new_tbl LIKE orig_tbl; The copy is created using the same version of the table storage format as the original table. The SELECT privilege is required on the original table. LIKE works only for base tables, not for views. CREATE TABLE ... LIKE does not preserve any DATA DIRECTORY or INDEX DIRECTORY table options that were specified for the original table, or any foreign key definitions.

davek