Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Voting Script, Possibility of Simplifying Database Queries

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

  • In the votes table, vote_id is a primary key
  • In the post table, post_id is a primary key.
  • Any other suggestions to speed things up?
like image 294
Sev Avatar asked Feb 07 '26 02:02

Sev


1 Answers

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.

like image 150
Quassnoi Avatar answered Feb 08 '26 16:02

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!