Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table with SELECT syntax in MySQL

I would like to know how MySQL interprets the CREATE TABLE syntax:

If I write:

CREATE TABLE tbl1 (
    `v1` int,
    `v2` int
     CONSTRAINT idx PRIMARY KEY (v1)
)
SELECT a, b FROM tbl2;
  • Does it determine which value goes into v1 and which goes into v2 by their order in the select statement?

  • Does it use the names I designate in the CREATE TABLE statement or does it take them from the select statement?

I have used the CREATE TABLE XX SELECT val FROM YY before but would like to know more specifically about the above syntax.

like image 205
Alex Avatar asked Aug 15 '12 02:08

Alex


People also ask

What is the syntax to create table in MySQL?

The general syntax for creating a table in MySQL is: CREATE TABLE [IF NOT EXISTS] table_name( column_definition1, column_definition2, ........, table_constraints ); Note: [IF NOT EXISTS] verifies if there is an identical table in the database. The query will not be executed if an identical table already exists.

What is the syntax of SELECT?

SELECT statements The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names.

How do I SELECT a database to create a table in MySQL?

The create database statement is: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )


1 Answers

With your current solution you'll get a table with the columns v1, v2, a, and b.

To see how it is done properly, see the "CREATE TABLE ... SELECT Statement" chapter in the official MySQL documentation.

So if you just want v1 and v2 with an index on v1, do it like this:

CREATE TABLE tbl1 (PRIMARY KEY (v1))
SELECT a v1,
       b v2
FROM tbl2;
like image 188
Michael Best Avatar answered Sep 30 '22 13:09

Michael Best