Reputation: 285
Sorry if I'm asking this, maybe it has a simple solution but I'm scratching my head for three days now and I can't find a good solution.
I have two tables, one defines "totals" and another table that defines "details".
Table_Totals
|item_id|user_rating| rating_count|
| 1 | 5.000| 5|
| 2 | 2.000| 3|
| 3 | 1.000| 5|
| 4 | 3.000| 2|
| 5 | 4.000| 8|
I can easily get the "rank" of each item_id by this query:
SELECT uo . * , (
SELECT COUNT( * )
FROM Table_Totals ui
WHERE (ui.user_rating, ui.item_id) >= ( uo.user_rating, uo.item_id )
) AS rank
FROM Table_Totals uo
WHERE item_id = 3
So, I get this (global rank):
|item_id|user_rating| rating_count|rank|
| 3 | 1.000| 5| 5|
Now, I have also this table (that defines "details"):
Table_Details
|item_id|category| players|
| 1 | arcade| 113|
| 2 | RPG| 31|
| 3 | arcade| 522|
| 4 | arcade| 100|
| 5 | MMORPG| 82|
My question is: how can I get the rank of a item_id BY category? How can I join these two tables and get something like this? (Keep in mind: item_id.Table_Totals = item_id.Table_Details).
I.E. rank for "arcade category":
|item_id|category| rank|
| 1 | arcade| 1|
| 3 | arcade| 3|
| 4 | arcade| 2|
What's the best way to accomplish something similar?
Thank in advance to all!
Upvotes: 1
Views: 743
Reputation: 21513
Assuming a 1 to 1 relationship, and using user variables something like this (not tested):-
SELECT a.item_id, a.category, @rank:=@rank + 1 as rank
FROM Table_Details a
INNER JOIN Table_Totals b
ON a.item_id = b.item_id
CROSS JOIN (SELECT @rank:=0) Sub1
WHERE category = 'arcade'
ORDER BY b.user_rating DESC
Upvotes: 1