5

I have a movies Postgres database, I want to efficiently list all movies played by an actor, And list all actors in a movie.

Currently I'm using these two SELECT statements (Which I bileive there is better way to do that):

SELECT title FROM movies,castings WHERE movies.id = castings.movieid and castings.actorid  = (SELECT id FROM actors where name = $name and sname = $sname);

SELECT name, sname FROM actors,castings WHERE actors.id = castings.actorid and castings.movieid  = (SELECT id FROM movies where title = $title);

The Database:

CREATE SEQUENCE directors_id_seq;
CREATE TABLE directors  (
    id BIGINT PRIMARY KEY DEFAULT nextval('directors_id_seq'),
    name TEXT,
    sname TEXT
);

CREATE SEQUENCE actors_id_seq;
CREATE TABLE actors (
    id BIGINT PRIMARY KEY DEFAULT nextval('actors_id_seq'),
    name TEXT,
    sname TEXT
);

CREATE SEQUENCE movies_id_seq;
CREATE TABLE movies (
    id BIGINT PRIMARY KEY DEFAULT nextval('movies_id_seq'),
    title TEXT NOT NULL,
    year INT NOT NULL,
    votes INT,
    score INT,
    director BIGINT NOT NULL REFERENCES directors (id)
);

CREATE TABLE castings   (
    movieid BIGINT REFERENCES movies (id),
    actorid BIGINT REFERENCES actors (id),
    ord INT,
    PRIMARY KEY (movieid, actorid)
);

How can I list all movies played by an actor? How can I list all actors played on a movie?

-- Thanks,

1 Answer 1

11

This should do it:

All movies played by an actor

SELECT M.*
FROM movies M
INNER JOIN castings C ON C.movieid = M.id
INNER JOIN actors A ON A.id = C.actorid
WHERE A.name = $name
AND A.sname = $sname

All actors played on a movie

SELECT A.*
FROM actors A
INNER JOIN castings C ON C.actorid = A.id
INNER JOIN movies M ON M.id = C.movieid
WHERE M.title = $title
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.