Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a table based on few columns of another table, but also add some additional columns

Tags:

mysql

I know I can do something like this:

CREATE TABLE new_table AS (
    SELECT field1, field2, field3
    FROM my_table
)

I'm wondering how do I add more columns to this create table SQL, that are not from my_table, but instead ones that I would write my self and which would be unique to this new_table only.

I know I could just make the table with the above SQL and then additionaly (after the command is completed) add the necessary columns, but am wondering if this all could be done in one command, maybe something like this (tried it like that, but didn't work):

CREATE TABLE new_table AS (
    (SELECT field1, field2, field3
    FROM my_table),
    additional_field1 INTEGER NOT NULL DEFAULT 1,
    additional_field2 VARCHAR(20) NOT NULL DEFAULT 1
)
like image 359
Nikola Avatar asked Sep 10 '12 07:09

Nikola


People also ask

How do you add a column to a table from another table in SQL?

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

How do I add multiple columns to an existing table?

You can add multiple columns to an SQL table using the ALTER TABLE syntax. To do so, specify multiple columns to add after the ADD keyword. Separate each column you want to add using a comma.

How do you create a table from another table?

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. The new table has the same column definitions. All columns or specific columns can be selected.


1 Answers

You can also explicitly specify the data type for a generated column:

See Create Table Select Manual

CREATE TABLE new_table
(
 additional_field1 INTEGER NOT NULL DEFAULT 1,
 additional_field2 VARCHAR(20) NOT NULL DEFAULT 1
)
AS
(
 SELECT id, val,
        1 AS additional_field1,
        1 AS additional_field2
 FROM my_table
);

Example: SQLFiddle

like image 147
Omesh Avatar answered Oct 21 '22 14:10

Omesh