SQL To Find Most Popular Category

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

    1) I assume the categories table also has category_id field, and the items table has an item_id or you won't be able to link the tables. 2) AS keyword is often optional

    SELECT c.name, SUM(ABS(v.value))
    FROM categories c
    INNER JOIN items i ON c.category_id = i.category_id
    INNER JOIN votes v ON v.item_id = i.item_id
    WHERE v.created_at BETWEEN DATE_SUB(NOW(), INTERVAL -7  DAYS) AND NOW()
    GROUP BY c.name
    ORDER BY 2 DESC
    LIMIT 10
    
    • The AS keyword is for making a synonym of the table name. Most times this is just a shorthand, but if you perform self-joins where the table is joined to itself, you need to distinguish them. And if two tables have the same field name, you need to specify which table's field you are using, thus c.category_id comes from the "c" table, which means the category table.
    • JOINS are essential. Start reading.
    • In my solution, I used DATE_SUB which is native to mySQL. I do not know how many other databases use that function, but all of them have something similar.
    • My query gives you the top ten categories with the most popular first. Note that the LIMIT N clause is how you do it in mySQL. In SQLServer, use TOP N after the SELECT keyword. In Oracle, it is done another way.
    • I took the absolute value of votes because you said include up or down votes.
    • ORDER BY 2 DESC means sort descending by the second column in the select. You can use the actual expression here, but that is more typing.
    • GROUP BY is necessary. Every column that is not a constant or aggregated with SUM, COUNT, MAX, etc. must appear in the GROUP BY clause if there are any aggregate functions used.

提交回复
热议问题