Home  >  Q&A  >  body text

Create table using SELECT syntax in MySQL

I want to know how MySQL interprets the CREATE TABLE syntax:

If it were written like this:

CREATE TABLE tbl1 (
    `v1` int,
    `v2` int
     CONSTRAINT idx PRIMARY KEY (v1)
)
SELECT a, b FROM tbl2;

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

P粉715228019P粉715228019479 days ago567

reply all(1)I'll reply

  • P粉741678385

    P粉7416783852023-07-21 20:29:10

    Based on the current solution, you will get a table with columns v1 v2 a and b.

    To learn how to do it correctly, see the "CREATE TABLE ... SELECT Statement" chapter, please refer to the MySQL official documentation. .

    So if you just want v1 and v2 to have an index on v1, like this:

    CREATE TABLE tbl1 (PRIMARY KEY (v1))
    SELECT a v1,
           b v2
    FROM tbl2;

    reply
    0
  • Cancelreply