0

我目前有两个查询:

$iQ = mysql_query("SELECT * FROM `movies` WHERE `released` > '" . $begin . 
    "' AND `released` < '" . $end . "' ORDER BY `views` DESC LIMIT 5");

while ($iR = mysql_fetch_array($iQ)) {
    $imageQ = mysql_query("SELECT * FROM `movie_image`
        WHERE `movie_id` = '" . $iR['id'] . "' AND `image_size` = 'thumb'
        AND `type` = 'poster' LIMIT 1");
}

我想把它放到一个查询中,如果movie_image 表中有行,我只想返回结果,这意味着结果集中不会返回没有图像的电影。

如何加入这两个查询,以便我可以使用第一个查询获取电影图像,并且仅在电影 ID 存在电影图像时才返回结果?

如果您不明白,请告诉我,我会尝试改写我的问题。

4

4 回答 4

0

如果您想选择其中一个匹配的图像,但不关心哪个(这就是您当前的查询所做的),您可以加入表和GROUP BY电影 id(我假设它UNIQUE在 中movies,例如主键):

SELECT   *
FROM     movies
    JOIN movie_image 
      ON movie_image.movie_id = movies.id
     AND movie_image.image_size = 'thumb'
     AND movie_image.type = 'poster'
WHERE    movies.released BETWEEN :begin AND :end
GROUP BY movies.id
ORDER BY views DESC
LIMIT    5
于 2012-05-13T06:58:13.117 回答
0
SELECT * FROM `movies`
    INNER JOIN `movie_image` ON `movie_image`.`movie_id` = `movies`.`id`
    WHERE `movies`.`released` > '" . $begin . "'
    AND `movies`.`released` < '" . $end . "'
    AND `movie_image`.`image_size` = 'thumb'
    AND `type` = 'poster' ORDER BY `movies`.`views` DESC LIMIT 5

此查询应该适合您。

于 2012-05-13T06:20:30.460 回答
0

首先,这里的关系是一对多的关系,所以你不能在一个查询中做到这一点。

其次,如果存在电影图像,要返回电影,您需要在第一个查询中检查,然后遍历第一个查询以获取与每部电影相关的图像。

$iq = "SELECT m.* FROM `movies` m 
      RIGHT JOIN `movie_images` mi ON mi.movie_id = m.movie_id
      WHERE `m.released` > '" 
      . $begin . "' AND `m.released` < '" . $end . "' GROUP BY `m.movie_id` ORDER BY `m.views` 
      DESC LIMIT 5";

$res = mysql_query($iq);
while($ir = mysql_fetch_assoc($res)){
  //get the images for each movie here
}
于 2012-05-13T06:23:39.510 回答
0

我认为这个查询可以帮助你。如果电影表标识符 = id(ms.id)。

SELECT mi.* FROM movie_image mi
    JOIN movies ms ON mi.movie_id = ms.id
    WHERE ms.released > '" . $begin . "'
    AND ms.released < '" . $end . "'
    AND mi.image_size = 'thumb' AND mi.type = 'poster'
    ORDER BY ms.views DESC LIMIT 5
于 2012-05-13T06:23:48.467 回答