如何在Postgres中根据外键选择数据?

时间:2017-08-03 23:57:31

标签: postgresql

我有一部电影Postgres数据库,我想有效地列出演员播放的所有电影,并列出电影中的所有演员。

目前我正在使用这两个SELECT语句 (我认为有更好的方法可以做到这一点):

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);

数据库:

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)
);

如何列出演员播放的所有电影? 如何列出电影中播放的所有演员?

- 谢谢,

1 个答案:

答案 0 :(得分:2)

这应该这样做:

演员播放的所有电影

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

所有演员都在电影上播放

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