从 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