开发者

Mysql ranking from two tables

So I have two tables, "participations" an开发者_高级运维d "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:

SET @rank := 0;
SELECT id, votes, rank
from (
  SELECT id, votes, (@rank := @rank + 1) as rank
  from (
    SELECT p.id, COUNT(v.id) as votes 
    FROM participations as p 
    JOIN votes as v on p.id = v.participation_id
    WHERE ... -- add your where clause, if any, here to eliminate completely from results
    GROUP BY v.participation_id 
    ORDER BY votes DESC
  ) x
) y
-- Now join to apply filtering to ranked results, for example:
JOIN participations p1 on p1.id = y.id
where p1.date between '2011-06-01' and now(); -- just making up an example
and p1.gender = 'female'; -- for example

Some explanation:

The phrase (@rank := @rank + 1) increments the variable and returns the result of the increment, which has been given the alias rank.

The x at the end is the alias of your query's results and is required by the syntax (but any alias will do - I just chose x). 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜