I have a voting script which stores the post_id and the user_id in a table, to determine whether a particular user has already voted on a post and disallow them in the future.
To do that, I am doing the following 3 queries.
SELECT user_id, post_id from votes_table where postid=? AND user_id=?
If that returns no rows, then:
UPDATE post_table set votecount = votecount-1 where post_id = ?
Then
SELECT votecount from post where post_id=?
To display the new votecount on the web page
Any better way to do this? 3 queries are seriously slowing down the user's voting experience
Edit
You can merge the first two queries:
UPDATE post
SET votecount = votecount - 1
WHERE post_id = ?
AND post_id NOT IN
(
SELECT post_id
FROM votes_table
WHERE user_id = ?
)
You still need to run the third one.
Make sure that you have a unique index or a PRIMARY KEY on votes_table (user_id, post_id) and post (post_id).
Most probably, your current query slowness is caused by absence of these indexes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With