Q:

Users Rating update, recalculation

I have a table with fields id, votes(for each users), rating.
Task: Counting user rating based on votes for him and for others. that is, each time i update the field votes needed recalculation field rating.
Which means some can be on the 3rd place. voted for him and that he would be stood up to 2rd place, and the other vice versa - from 2 to 3. (in rating fiels)
How to solve this problem? Each time update the field to count users ratings on php and do a lot of update query in mysql is very expensive.

A:

If you want to get the ratings with a select without having a rating column, then this is the way. However from a performance perspective I cannot guarantee this will be your best option. The way it works is that if two users have the same amount of votes they will have the same rating and then it will skip ahead the necessary number for the next different rating:
set @rating:=0;
set @count:=1;

select id,
case when @votes<>votes then @rating:=@rating+@count
else @rating end as rating,
case when @votes=votes then @count:=@count+1
else @count:=1 end as count,
@votes:=votes as votes
from t1
order by votes desc

sqlfiddle
This gives you an extra column which you can ignore, or you could wrap this select in to a subquery and have:
select t2.id,t2.votes,t2.rating from (
select id,
case when @votes<>votes then @rating:=@rating+@count
else @rating end as rating,
case when @votes=votes then @count:=@count+1
else @count:=1 end as count,
@votes:=votes as votes
from t1
order by votes desc) as t2

but the sqlfiddle is strangely giving inconsistent results so you'd have to do some testing. If anyone knows why this is I'd be interested in knowing the reason.
If you want to get the rating for just one user then doing the subquery option and using a where after the from should give you the desired result. sqlfiddle - but again, inconsistent results, run it a few times and sometimes it gives rating as 10 other times as 30. I think testing in your db to see what happens will be best.

