admin

SQL:控制返回多少记录

sql

我有一个电影数据库,其中包含电影,演员和导演的表格。每部电影在电影表中占据一行。几乎我所有的查询都需要连接到其他表,以使LIMIT
50(偏移量为0)的查询返回大约4部电影的完整数据。下面是一个示例查询。我如何修改此设置以确保获取恰好10部电影的数据?

SELECT movie.id, movie.title, star.name, star.name_url, dir.name, 
       dir.name_url, genre.name, genre.name_url 
FROM movie 
        LEFT JOIN actor 
             ON (movie.id = actor.movie_id) 
        LEFT JOIN person AS star 
             ON (actor.person_id = star.id) 
        LEFT JOIN director 
             ON (movie.id = director.movie_id) 
        LEFT JOIN person AS dir 
             ON (director.person_id = dir.id) 
        LEFT JOIN genre_classification 
             ON (movie.id = genre_classification.movie_id) 
        LEFT JOIN genre 
             ON (genre_classification.genre_id = genre.id)
WHERE (movie.id > 0) 
ORDER BY movie.id 
LIMIT 50 OFFSET 0;

我正在使用PostgresSQL,可能没关系。


阅读 248

收藏
2021-07-01

共1个答案

admin

您去了(未体验):

SELECT movie.id, movie.title, star.name, star.name_url, dir.name, 
       dir.name_url, genre.name, genre.name_url 
FROM 
        (SELECT * FROM movie WHERE movie.id > 0 ORDER BY movie.id LIMIT 10) movie
        LEFT JOIN actor 
             ON (movie.id = actor.movie_id) 
        LEFT JOIN person AS star 
             ON (actor.person_id = star.id) 
        LEFT JOIN director 
             ON (movie.id = director.movie_id) 
        LEFT JOIN person AS dir 
             ON (director.person_id = dir.id) 
        LEFT JOIN genre_classification 
             ON (movie.id = genre_classification.movie_id) 
        LEFT JOIN genre 
             ON (genre_classification.genre_id = genre.id)

编辑:通过将所有条件放入子选择中,您无法控制源表中的哪些数据movie将用于JOIN。在性能方面,这也应该更快。

2021-07-01