简体   繁体   中英

How to count UP votes together and then select from database ORDER by UP votes

I have voting system on my website, it stores each users vote in table called skmp_voting each record in this database has id , item_id (this is id of article user voted on), and vote_value . vote_value depend's on what users did, if they voted up value is "1" if they voted down value is "-1".

I have toparticles.php page where I wan't to display top articles, so articles that have more up votes. Here is my mysql query to get top articles I have now:

SELECT stories.*, skmp_votes.vote_value FROM stories 
JOIN skmp_votes ON stories.id = skmp_votes.item_id 
ORDER BY skmp_votes.vote_value DESC

It select's article information from other table called stories and put's it against vote_value from skmp_votes table.

I'm pretty confident that this isn't right, as it selects vote_value that is equal to 1 or something, so I need to somehow count all vote_values together and then use mysql query to get top articles.

It depends on your voting table. As I imagined, it has a row for each vote. In this case, you'll have to do a sum for the votes wich match an article. ie

SELECT SUM(vote_value) as 'total_votes' FROM skmp_voting WHERE item_id='$article_id';

You use SUM instead of COUNT becouse you want to substract the value from the negative votes.

EDIT: complementing the answer

This following Query will get you every article and its total votes, ordered by the total votes (the most voted articles at the top)

SELECT stories.*, SUM(skmp_votes.vote_value) as 'total_votes' FROM stories 
  JOIN skmp_votes ON stories.id = skmp_votes.item_id 
  ORDER BY skmp_votes.total_votes DESC

To get, say the 5 most voted articles, you just add at the end LIMIT 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM