11

I have two tables with the same columns.

I can merge them with UNION

select * from  table1
union
select * from table2;

How do I create a new table with the same contents and columns as that query?

Matt Fenwick
  • 46,727
  • 21
  • 123
  • 189

3 Answers3

25

You can use CREATE TABLE ... SELECT statement.

CREATE TABLE new_table
  SELECT * FROM table1
    UNION
  SELECT * FROM table2;
Devart
  • 115,199
  • 22
  • 161
  • 180
5
create table new_table as
select col1, col2 from table1 
union 
select col1, col2 from table2

Make sure you select same set of columns from tables in union.

Husain Basrawala
  • 1,664
  • 14
  • 20
  • 1
    mysql throws an error if you try to wrap the union query in parenthesis. omitting the parenthesis did the trick for me, as suggested by @devart's answer – s2t2 Jul 19 '13 at 20:58
1

Or even you can explicitly define create table (we generally use in our project).

CREATE TABLE IF NOT EXISTS auditlog (

user_id varchar(30) NOT NULL default '',

user_ip varchar(255) NOT NULL default '',

........ ........

KEY ie1 (user_id) )

union=(auditlog_2,auditlog_3,auditlog_4) engine=merge insert_method=last;

kkjava
  • 96
  • 2
  • 7