SQL To Find Most Popular Category

前端 未结 6 690
面向向阳花
面向向阳花 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:52

    SELECT c.name, sum(v.value) as cnt
     FROM categories c
     JOIN items i ON i.category_id = c.id
     JOIN votes v ON v.item_id = i.id
     WHERE v.created_at > #{1.week.ago}
     GROUP BY c.name 
     ORDER BY cnt DESC LIMIT 5;
    

    Edit: good point andrew, I fixed the query

提交回复
热议问题