SQL To Find Most Popular Category

前端 未结 6 753
面向向阳花
面向向阳花 2021-01-20 00:04

I have 3 tables in my DB (MySQL).

categories (name:string)
items (name:string, category_id:int)
votes (value:int, item_id:int, created_at:datetime)
         


        
6条回答
  •  长情又很酷
    2021-01-20 00:59

    This is what I ended up using (slightly modified version of @akf's answer). The other answers were great also, but this one seemed the simplest to me as a novice. I find it interesting that it doesn't use any joins? Would not have thought this was possible. I like how clean and simple it is.

    SELECT c.*, SUM(ABS(v.vote)) AS score
    FROM categories c,items i, votes v
      WHERE c.id = i.category_id
      AND i.id = v.item_id
      AND v.created_at > '#{1.week.ago}'
    GROUP BY c.id
    ORDER BY score DESC LIMIT 5;
    

    (I forgot to mention in the question that each table has an 'id' column, which you can see being used here.)

    Summing the absolute value of the vote value works in this case since there are positives and negatives as some posters correctly pointed out, but I was thinking it would be even simpler to just count the number of vote records in the database. I tried "COUNT(v) AS score" but this didn't work. If anyone knows how please post a comment. Thanks everyone!

提交回复
热议问题