Ilja Ilja - 1 year ago 51
SQL Question

Need support with logic behind "approve post if 10 people like it" feature

Right now I have a voting system on my website that stores all votes in a votes table. in votes table I have a field named item_name which contains id of article that was liked. All article information including it's id is located in a stories table. In votes table each there is a field named vote_value which can be 1 and -1 and depending on what user put for vote (like / dislike).

I need to somehow sum up all records for certain article and if they sum up as 10 or more make article approved. To approve article I have a field in stories table which is named as showing it can have two values 0 - unproved 1 - approved. So somehow I need to make it so once an article gets 10 likes (as a sum of all records from votes table) set showing to 1 (showing is in a stories table).

Preferably without any queries, say make database check for sums of vote_value of article that has a showing = 0 (and ignore ones that have showing = 1, so less server resources are used) . I'm not sure if this is a lot to do for a server, maybe it's not the most efficient way.

EDIT: Users can un-vote and change vote value if they like (e.g. they liked the post, but they can change it to unlike).

My Database Structure:


enter image description here


enter image description here

Answer Source
UPDATE stories SET showing = 1 WHERE id IN (SELECT id,  SUM (vote_value) as total_votes from votes  GROUP BY item_name WHERE total_votes  > 10)

What I think will be efficient (depending on the amount of voting):

When a vote is cast:

Insert into votes set vote_value = '-1' where id = xx;
UPDATE stories SET showing = 1 WHERE id IN (SELECT id,  SUM (vote_value) as total_votes from votes WHERE id=xx AND total_votes  > 10);

That last one could be broken up with PHP, because this is a bit of a strange way of doing it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download