简体   繁体   English

如何一起计算UP票数,然后按UP票数从数据库ORDER中选择

[英]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 . 我的网站上有投票系统,它将每个用户的投票存储在名为skmp_voting的表中,该数据库中的每个记录都有iditem_id (这是用户投票的文章ID)和vote_value vote_value depend's on what users did, if they voted up value is "1" if they voted down value is "-1". 如果用户投票否定值为“ -1”,则vote_value取决于用户的操作。

I have toparticles.php page where I wan't to display top articles, so articles that have more up votes. 我有toparticles.php页面,在这里我不会显示热门文章,因此那些文章的投票最多。 Here is my mysql query to get top articles I have now: 这是我的mysql查询以获得我现在拥有的热门文章:

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. 它从称为故事的其他表中选择文章信息,并将其与skmp_votes表中的表决值相对

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. 我非常有信心这是不对的,因为它选择的表决值等于1或类似的值,所以我需要以某种方式将所有表决值相加,然后使用mysql查询来获得热门文章。

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. 您使用SUM而不是COUNT您要从否定票中减去该值。

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 要获得5个投票最多的文章,只需在末尾添加LIMIT 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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