SQL To Find Most Popular Category

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

    try this. use group by with the name of the category. i have commented out the created at clause as you specified, you can uncomment it if you want to use it.

     SELECT c.name, SUM(ABS(v.item_id)) 
     FROM categories c,items i, votes v
     WHERE c.name = i.name
        AND i.item_id=v.item_id
        --AND v.created_at > #{1.week.ago}
     GROUP BY c.name 
     ORDER BY SUM(ABS(v.item_id)) DESC LIMIT 5;
    

    you will notice that i did not use the JOIN keyword but instead filtered the results of the query using only WHERE clauses, which might be easier to understand. if you want to learn more about JOINs, here is a tutorial.

    Here, too, is a tutorial on SQL aliases (the AS clause). in fact, there are a bunch more tutorials on this site for a bunch of different SQL topics that are not platform dependent.

    edit: fixed as per comments, added the abs function,

提交回复
热议问题