0

这是我在这里提出的问题的后续行动。使用相同类型的查询,如果存在“genre.name = 'Classic Movies' 和 '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)
4

1 回答 1

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 部具有匹配类型“经典电影”的电影。

当然,这仍然会返回超过 10 行,因为您正在JOIN寻找演员、导演、其他类型等。但是,您应该在结果集中有多达 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)
于 2012-08-30T16:52:08.453 回答