'How to grab the ID of an artist so i can insert the album into the database with the artist's ID?
Here is my schema:
CREATE TABLE artists
(
id serial PRIMARY KEY,
name varchar(40) NOT NULL UNIQUE
);
CREATE TABLE albums
(
id serial PRIMARY KEY,
name varchar(40) NOT NULL,
artist integer NOT NULL,
FOREIGN KEY(artist) REFERENCES artists(id)
);
CREATE TABLE songs
(
id serial PRIMARY KEY,
name varchar(40) NOT NULL,
album integer NOT NULL,
FOREIGN KEY(album) REFERENCES albums(id)
);
This is what I'm doing:
INSERT INTO artists (name)
VALUES ('Dio') ON CONFLICT DO NOTHING;
INSERT INTO artists (name)
VALUES ('Amorphis') ON CONFLICT DO NOTHING;
SELECT id FROM artists WHERE name = 'Dio';
SELECT id FROM artists WHERE name = 'Amorphis';
INSERT INTO albums (name, artist) VALUES ('Holy Diver', 1) ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist) VALUES ('Dream Evil', 1) ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist) VALUES ('Halo', 2) ON CONFLICT DO NOTHING;
Right now I'm inserting into albums by looking at the table for the artist ID and typing manually. How can I do this automatically?
My application will receive the song title, artist name and album name. So it will need to look for the artist ID if the artist exists and if not, create the artist, then grab the ID of said artist and put into the INSERT INTO
albums statement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|