41 lines
965 B
SQL
41 lines
965 B
SQL
CREATE TABLE IF NOT EXISTS genres (
|
|
genre_id SERIAL PRIMARY KEY,
|
|
name VARCHAR(30) NOT NULL UNIQUE
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS publishers (
|
|
publisher_id SERIAL PRIMARY KEY,
|
|
name VARCHAR(50) NOT NULL UNIQUE
|
|
);
|
|
|
|
INSERT INTO genres (name)
|
|
SELECT DISTINCT genre
|
|
FROM board_games
|
|
WHERE genre IS NOT NULL;
|
|
|
|
INSERT INTO publishers (name)
|
|
SELECT DISTINCT publisher
|
|
FROM board_games
|
|
WHERE publisher IS NOT NULL;
|
|
|
|
ALTER TABLE board_games
|
|
ADD COLUMN genre_id INT,
|
|
ADD COLUMN publisher_id INT;
|
|
|
|
UPDATE board_games
|
|
SET genre_id = g.genre_id
|
|
FROM genres g
|
|
WHERE board_games.genre = g.name;
|
|
|
|
UPDATE board_games
|
|
SET publisher_id = p.publisher_id
|
|
FROM publishers p
|
|
WHERE board_games.publisher = p.name;
|
|
|
|
ALTER TABLE board_games
|
|
DROP COLUMN genre,
|
|
DROP COLUMN publisher;
|
|
|
|
ALTER TABLE board_games
|
|
ADD CONSTRAINT fk_genre FOREIGN KEY (genre_id) REFERENCES genres (genre_id),
|
|
ADD CONSTRAINT fk_publisher FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id); |