开发者

Creating a numerical order index on a MySQL table

I have a table with (essentially) 3 columns - name, votes an开发者_如何学Cd rank. I want to order the table by votes and then update 'rank' to reflect this order, so that the one with the most votes will have rank set to 1, the second most votes to 2 etc.

I can do this in PHP but it seems pretty wasteful - is there a way to do this with one SQL query without having to manually process every record in PHP?


Assuming you don't care about ties you can just calculate the rank dynamically in your queries instead of storing it.

 SET @rank=0;

 SELECT @rank:=@rank+1 AS rank, name, votes
 FROM yourTable
 ORDER BY votes DESC;


Although @johnfx gave you the correct answer I think you will be interested reading the comments of this article - http://arjen-lentz.livejournal.com/55083.html where various ranking problems are solved.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜