假设我有这张表:
ID Score
1 345
2 5
3 76
4 45
5 85
6 175
7 209
这是我的疑问:
SELECT * FROM posts ORDER BY Score DESC
如何获得每个行的排名/位置?
答案 0 :(得分:1)
您可以像上面这样使用像@OMG Ponies这样的技术:
SELECT posts.*, @row:=@row+1 as 'rank' FROM posts, (SELECT @row:=0) r ORDER BY posts.Score DESC
答案 1 :(得分:0)
如果您在代码下方运行,则会看到新列Position
与Rank
SELECT ID, Score,
(SELECT COUNT(distinct u2.Score) FROM myTable u2
WHERE
u2.Score > u1.Score) + 1 AS position FROM myTable u1
ORDER BY position
如果您有任何问题,请告诉我......