Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CREATE TABLE LIKE A1 as A2

Tags:

mysql

I want to create a new table with properties of an old table and without duplicates. I want to do something like this:

CREATE TABLE New_Users  LIKE Old_Users,  AS (SELECT * FROM Old_Users GROUP BY ID) ; 

But the above is not working. Can anybody modify it to work?

like image 290
Jigberto Avatar asked Apr 13 '12 20:04

Jigberto


People also ask

Can we CREATE TABLE using like?

The SELECT privilege is required on the original table. LIKE works only for base tables, not for views. You cannot execute CREATE TABLE or CREATE TABLE ... LIKE while a LOCK TABLES statement is in effect.

How do I create a table from one table to another in SQL?

Answer: To do this, the SQL CREATE TABLE syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2); For example: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1=2);

How will you create a table with the same structure as another table in Oracle?

Question: How can I create an Oracle table from another table without copying any values from the old table? Answer: To do this, the Oracle CREATE TABLE syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2);


1 Answers

Your attempt wasn't that bad. You have to do it with LIKE, yes.

In the manual it says:

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.

So you do:

CREATE TABLE New_Users  LIKE Old_Users; 

Then you insert with

INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID; 

But you can not do it in one statement.

like image 81
fancyPants Avatar answered Sep 22 '22 19:09

fancyPants