2012-07-04 97 views
0
select 
    user_id, 
    @pos:=(@pos+1) as new_position, 
    (coins+total_item_costs) as wealth 
from user_ledger 
join users using (user_id),(select @pos:=0) p 
ORDER BY wealth DESC 
limit 10; 

+---------+--------------+------------+ 
| user_id | new_position | wealth  | 
+---------+--------------+------------+ 
|  19 |   19 | 1112823871 | 
|  11 |   11 | 13318047 | 
|  8 |   8 | 7292407 | 
|  6 |   6 | 6122746 | 
|  27 |   27 | 5271889 | 
|  23 |   23 | 5263050 | 
|  9 |   9 | 5171734 | 
|  3 |   3 | 5136092 | 
|  15 |   15 | 5097488 | 
|  4 |   4 | 5089487 | 
+---------+--------------+------------+ 
10 rows in set (0.01 sec) 

new_position不正确.. 有什么不对? :)mysql查询评分系统

ps。请不要告诉我使用临时表

回答

0

应该事先做好ORDER BY的位置。

SELECT user_id,@pos:=(@pos+1) as new_position,wealth FROM (
     select user_id,(coins+total_item_costs) as wealth from user_ledger join users 
     using (user_id) ORDER BY wealth DESC limit 10) a,(select @pos:=0) p 
+0

是的,这工作,但我真的不希望使用临时表(甚至隐藏)..你可以认为没有它的查询? –

+0

@IgorK:如果你能解释*为什么你不想使用物化表? – eggyal

+0

@eggyal:例如,因为我将使用select作为'INSERT INTO .. SELECT'语句的一部分,并且不想使用临时存储器的结果:) –