I currently have two queries:
$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");
}
I want to put this in to one query, and I only want to return results IF there are rows in the movie_image table, meaning movies without images won't be returned in the result set.
How can I go about joining these two queries, so I can get the movie image with the first query, and only return the result if there IS a movie image present for the movie ID?
Let me know if you don't understand and I'll try rephrase my question.
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
This query should work for you.
First thing the relation here is a one-many relationship so you cannot do it in one query.
Second, to return the movies if there is a movie image present you need to check that in the first query, then iterate through the first query to get the images related to each movie.
$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
}
I thinks this query helps you. If movies table identifier = 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
If you want to select one of the matching images, but don't care which (that's what your current query does), you can just join the tables and GROUP BY
movie id (I assume that it's UNIQUE
in movies
, e.g. the primary key):
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