简体   繁体   中英

FOREIGN KEY in CREATE NEW TABLE AS in SQL

I am following https://www.w3schools.com/sql/sql_create_table.asp to create new table AS and my task is to add foreign key into it. It fails and gives syntax error while I try to do it.

CREATE TABLE movie_genre AS 
SELECT movie.movie_id, movie.genres
FROM movie
FOREIGN KEY (movie_id) REFERENCES movie(movie_id);

There is no guide how to put it when using AS

CREATE TABLE [...] FROM do not support any constraints/foreign keys.

But do not worry. You can issue follow up ALTER TABLE to add necessary constraints/foreign keys.

Correct way to make this is to add foreign key afterwards.

CREATE TABLE movie_genre
 AS (SELECT movie.movie_id, movie.genres
    FROM movie
    );

ALTER TABLE movie_genre
  ADD FOREIGN KEY (movie_id)
    REFERENCES movie(movie_id);

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