So I have two tables, “participations” and “votes”.
Every row in the table “votes” contains a “participation_id” to reference the participation for which the vote was cast.
Now, I want to be able to select the absolute ranking a participation has based on the number of votes it has.
Normally, this would be simple just using this simple query:
SELECT p.id, COUNT(v.id) as votes
FROM participations as p
JOIN votes as v on p.id = v.participation_id
GROUP BY v.participation_id
ORDER BY votes DESC;
BUT, I have to be able to add some WHERE-clauses in there somewhere. So if I do that, I’ll just get a relative ranking (ie. its ranking relative to the filtered rowset)
Does anybody know if this is possible with just one query!? (ofcourse subqueries are allowed) I hope this question makes sense to anyone.
You need to use a variable, which is incremented every row, and select from your query’s results, like this:
Some explanation:
The phrase
(@rank := @rank + 1)increments the variable and returns the result of the increment, which has been given the aliasrank.The
xat the end is the alias of your query’s results and is required by the syntax (but any alias will do – I just chosex). It is necessary to use the inner query, because that is what provides the ordering – you can’t add rank until that’s been done.Note:
Any where clause or other order by processing you want must happen in the inner query – the outer query is only for the rank processing – it takes the final query row set and adds a rank to it.