Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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:</p> <pre><code>set @rating:=0; set @count:=1; select id, case when @votes&lt;&gt;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 </code></pre> <p><a href="http://sqlfiddle.com/#!2/7c2f8/1" rel="nofollow">sqlfiddle</a></p> <p>This gives you an extra column which you can ignore, or you could wrap this select in to a subquery and have:</p> <pre><code>select t2.id,t2.votes,t2.rating from ( select id, case when @votes&lt;&gt;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 </code></pre> <p>but the <a href="http://sqlfiddle.com/#!2/a7470/18" rel="nofollow">sqlfiddle</a> 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.</p> <p>If you want to get the rating for just one user then doing the subquery option and using a <code>where</code> after the <code>from</code> should give you the desired result. <a href="http://sqlfiddle.com/#!2/7c2f8/5" rel="nofollow">sqlfiddle</a> - 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload