I have 3 tables with the following columns :
* users : user_id
* votes : user_id, creation_id
* creations : creation_id, creation_points
Each user can vote one time for each creation. When a user vote, this happens :
- Table
votes: Insert a new line withuser_idandcreation_id(so we can check if the user has already voted for this creation) - Table
creations: Add +1 to rowcreation_pointsfor the concerned creation
But now, I want that when the user has successfully voted for a creation, it displays him the next creation for which he didn’t vote yet. How can I achieve that ?
I tried this way :
- Select the next
creation_idfromcreationstable (wherecreation_idis bigger than the currentcreation_id) - Check if the couple
creation_id&user_idalready exists in thevotestable. If it exists, retry from 1).
The problem with this method is that it needs a lot of queries if the user has already voted for the next creation. It also create an infinite loop if he has already voted for all the creations. Is there others alternatives ?
If I understand how you are handling it, you seem to be on the right track by storing
votesas auser_idandcreation_id. To get the next available creation, use aLIMIT 1query that excludes the already voted-for creations:This method uses a
NOT IN()subquery:Similar thing using
NOT EXISTSinstead: