john
john

Reputation: 1280

Calculating top 5 users with the most points in the current category or category below it

I have a points system on my website and points are gained for different achievements within the different website categories. Categories can have sub-categories and parent categories using the 'category_relations' table with 'links_to' and 'links_from' fields holding the relevant category_id's.

What i'd like to do is fetch the top 5 users with the most points in the current category and any categories directly below it.

My 'points_awarded' table has all the records of any points awarded and to what users from what categories:

user_id,
points_amount, plus (tinyint boolean if it's points added or not),
minus (tinyint boolean if it's point penalty or not),
category_id

I don't really know where to start with this. Will i need to have two queries, one to fetch all sub category id's, and then one to use that to run another query to fetch SUM() of the points used? Is it possible to do it in one query?

Upvotes: 2

Views: 116

Answers (1)

Okonomiyaki3000
Okonomiyaki3000

Reputation: 3696

I'd need more information about your database tables to be sure but something like this will probably work:

SELECT 
    `user_id`, 
    SUM(IF(`plus`, `points_amount`, 0)) - SUM(IF(`minus`, `points_amount`, 0)) AS `points`
FROM 
    `points_awarded`
WHERE
    `user_id` = $user_id
    AND (
        `category_id` = $cat_id
        OR `category_id` IN(
            SELECT `links_to`
            FROM `category_relations`
            WHERE `links_from` = $cat_id
        )
    )
GROUP BY `user_id`

I'm curious though, why do you have a plus field and a minus field? If plus is false, can't we assume it's minus? Why have either field anyway, why not just make points_amount a signed field?

Upvotes: 2

Related Questions