如何从 MySQL 中现有的 table 创建另一个 table?
How do I create another table from an existing table in MySQL?
我有一个名为 UserInfo 的 table,如下所示:
Userid Job Age
John A 35
Sarah B 27
我想创建另一个这样的 table 称为 UserScores(分数为空):
Userid Score
John
Sarah
其中 userid 列与其他列完全相同 table。我将如何使用 SQL 执行此操作?这是我试过的:
CREATE TABLE UserScores AS
SELECT userid, score
FROM user
这是我的错误信息:
我还需要将用户 ID 作为我的 UserScores table 中的主键。我该怎么做?提前致谢。
您将 NULL 作为值添加到下面的分数中,并在创建 table userscores
后添加主 kley
CREATE TABLE user (userid INT)
INSERT INTO user VALUES (1)
CREATE TABLE UserScores AS
SELECT userid, NULL AS score
FROM user
ALTER TABLE UserScores
ADD PRIMARY KEY (userid);
db<>fiddle here
EDIt
您还应该在创建
中定义分数类型
CREATE TABLE UserScores (userid int, scrore int) AS
SELECT userid, NULL AS score
FROM user
我有一个名为 UserInfo 的 table,如下所示:
Userid Job Age
John A 35
Sarah B 27
我想创建另一个这样的 table 称为 UserScores(分数为空):
Userid Score
John
Sarah
其中 userid 列与其他列完全相同 table。我将如何使用 SQL 执行此操作?这是我试过的:
CREATE TABLE UserScores AS
SELECT userid, score
FROM user
这是我的错误信息:
我还需要将用户 ID 作为我的 UserScores table 中的主键。我该怎么做?提前致谢。
您将 NULL 作为值添加到下面的分数中,并在创建 table userscores
后添加主 kleyCREATE TABLE user (userid INT)
INSERT INTO user VALUES (1)
CREATE TABLE UserScores AS SELECT userid, NULL AS score FROM user
ALTER TABLE UserScores ADD PRIMARY KEY (userid);
db<>fiddle here
EDIt
您还应该在创建
中定义分数类型CREATE TABLE UserScores (userid int, scrore int) AS
SELECT userid, NULL AS score
FROM user