I have a MySQL database with two tables (simplified for this question):
movies table columns: id, title, duration, description, created_at, updated_at
rentals table columns: id, movie_id, status, created_at, updated_at
The rental status is either 'CHECKED OUT' or 'RETURNED', so a movie is available if it either has no associated rental, or all of its associated rentals have a status of 'RETURNED'. How do I query available movies? Right now I've got this:
SELECT rentals.id,rentals.status,movies.*
FROM `movies`
LEFT OUTER JOIN rentals ON movies.id = rentals.movie_id
AND movies.kiosk_id = rentals.kiosk_id
WHERE (`movies`.kiosk_id = 1
AND (rentals.id is null or rentals.status != 'CHECKED OUT'));
The problem is this query returns multiple records for a movie if it's been checked out several times, so my ORM gives me duplicate movie objects. Is there some way to specify that I only want unique movie.id's? Should I have some different database schema? Or should I sort it out programatically (seems like it would be too slow)?