從 SELECT 中建立表

你可以通過在 CREATE TABLE 語句末尾新增 SELECT 語句來建立另一個表:

CREATE TABLE stack (
    id_user INT,
    username VARCHAR(30),
    password VARCHAR(30)
);

在同一個資料庫中建立一個表:

-- create a table from another table in the same database with all attributes
CREATE TABLE stack2 AS SELECT * FROM stack;

-- create a table from another table in the same database with some attributes
CREATE TABLE stack3 AS SELECT username, password FROM stack;

從不同的資料庫建立表:

-- create a table from another table from another database with all attributes
CREATE TABLE stack2 AS SELECT * FROM second_db.stack;

-- create a table from another table from another database with some attributes
CREATE TABLE stack3 AS SELECT username, password FROM second_db.stack;

NB

要建立與另一個資料庫中存在的另一個表相同的表,你需要指定資料庫的名稱,如下所示:

FROM NAME_DATABASE.name_table