简体   繁体   中英

How do I create another table from an existing table in MySQL?

I have a table called UserInfo like this:

Userid     Job     Age
John       A       35
Sarah      B       27

and I want to create another table like this called UserScores (score is null):

Userid     Score
John       
Sarah      

Where the userid column is the same exact as the other table. How would I do this with SQL? This is what I tried:

CREATE TABLE UserScores AS
    SELECT userid, score
    FROM user

Here's my error message: 在此处输入图像描述

I need the userid to be the primary key in my UserScores table as well. How would I do this? Thanks in advance.

You add NULL as value to scores as below and add the promary kley after creatuing the table userscores

 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

you should also define the type of score in the create

CREATE TABLE UserScores (userid  int, scrore int) AS
    SELECT userid, NULL AS score
    FROM user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM