SQL:控制返回的记录数量第2部分

时间:2012-08-30 16:41:21

标签: sql database postgresql

这是我提出的here问题的后续跟进。使用相同类型的查询,如果有像'genre.name ='经典电影'和'star.name = Humphrey Bogart'这样的限制,如何确保我收到10部电影。需要说明的是,无论过滤限制是什么,查询都必须返回10部电影的数据。

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)

1 个答案:

答案 0 :(得分:1)

问题是你是通过这个子选择从数据库中选择10部电影的列表:

(SELECT * FROM movie WHERE movie.id > 0 ORDER BY movie.id LIMIT 10) movie

如果您尝试使用该子选择之外的WHERE子句进一步过滤该列表,则可能会使少于这10行,因为并非所有10都符合您的条件。您可以将新标准添加到子选择中,如下所示:

(SELECT * FROM movie m INNER JOIN genre_classification g on g.movie_id = m.id and g.name = 'Classic Movies' WHERE m.id > 0 ORDER BY m.id LIMIT 10) movie

这会做同样的事情,但为您提供(最多)10部电影,这些电影具有匹配的“经典电影”类型。

当然,由于你JOIN演员,导演,其他类型等等,这仍然会返回超过10行。但是,你应该在结果中有多达10个不同的电影ID集。

完整查询:

SELECT movie.id, movie.title, star.name, star.name_url, dir.name, 
       dir.name_url, genre.name, genre.name_url 
FROM 
        (SELECT * FROM movie m INNER JOIN genre_classification g on g.movie_id = m.id and g.name = 'Classic Movies' WHERE m.id > 0 ORDER BY m.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)