2009-02-02 47 views
7

我有一個users表,它有一個名爲money_sent的列。我想按照money_sent的降序排列這張表,然後找出具體用戶的「等級」。MySQL:獲取特定行的行號(排名)

例如,只有111人花的錢比用戶12392,所以他們會排名112

我怎麼能查詢這個?

回答

13

如何:

SELECT count(*) FROM users WHERE money_sent < (
    SELECT money_sent FROM users WHERE user = 'joe' 
); 
+0

太好了!一個簡單而有效的想法! – 2013-09-03 14:26:53

2
SELECT Row,user, money_sent 
FROM (SELECT @row := @row + 1 AS Row, user, money_sent 
     FROM table1 order by money_sent desc) 
As derived1 
2

如果你也想與該用戶的排名相處了用戶的行,你可以使用這樣的事情:

SELECT u1.*, COUNT(u2.user) 
FROM users u1 
    LEFT OUTER JOIN users as u2 ON (u1.money_sent < u2.money_sent) 
GROUP BY u1.user;