I’m creating a small voting application. I need to get the images and their vote counts from one table, and then check another vote table to see if the user has already voted for each of these images already.
To get the images from the image table I’m doing this:
SELECT id, file_name, total_votes
FROM _images
WHERE approved = 1
ORDER BY total_votes DESC
LIMIT ".($page*5).", 5"
But I also need to check in the “vote” table that their userid isn’t already associated with the (image) id from this query. I only need to show 5 images at a time, hence the LIMIT applied to the first query.
I’m not sure whether I need to do some joining or multiple queries.
my vote table has fields:
- id
- voter_id
- image_id
EDIT:
Thanks for all your feedback.
Some more info:
total_votes felt dirty when I put it in there, but I couldn’t work out a better way to count up the votes each time. Wouldn’t it be inefficient if every time there was a vote cast, or a request to view the leaderboard that all the votes had to be tallied and sorted?
Forgive me for my sins – I’m not a database programmer!
Using LEFT JOIN/IS NULL:
Using
NOT EXISTSUsing
NOT INSuggested Reading: