开发者

Select count votes for each object and top voted objects

开发者 https://www.devze.com 2023-01-29 03:10 出处:网络
I have two t开发者_StackOverflowables : VOTE with fields pk:id, fk:uid, date and SUBMISSION with fields pk:id, ....

I have two t开发者_StackOverflowables :

VOTE with fields pk:id, fk:uid, date and SUBMISSION with fields pk:id, ....

Tables have 1to1 relation on uid<-id fields. How I can now query for :

  • list of objects together with their score
  • list of 10 top rated objects ordered by score ?


    SELECT s.*,
           COUNT(*) AS cnt
      FROM SUBMISSION s
INNER JOIN VOTE v ON s.id = v.uid
  GROUP BY s.id
  ORDER BY cnt DESC
     LIMIT 10

Without ORDER BY and GROUP BY clauses you'll just retrieve all the submissions with votes count.

But I highly recommend you to create votes_count field in the SUBMISSION table and maintain it with trigger/code to store the precalculated count of votes there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号