MYSQL - 具有用户定义变量的select子句在子查询中使用时不返回相同的结果

时间:2016-07-06 20:21:02

标签: mysql subquery ranking user-variables

我在MYSQL下遇到了一些麻烦,希望能在这里找到答案。

我有一些分数表,并且想要查询排名靠近当前用户的用户。例如,如果当前用户排名#85,我想得到排名为80到90的用户。

这是我的分数表的摘录

.ebextensions/ignore_4xx.config

当然,得分表不具有等级,它是在我查询数据库时动态计算的。 我有一个用户表,给我它的名字(和一些其他信息,与我的问题无关):

uuID  |  game   |  score  |attempt  |lastAttempt  
id3   |Gravity  |  1186   |156      |2016-06-30 23:58:09 
id2   |Gravity  |  1376   |2        |2015-07-18 22:45:23 
id1   |Gravity  |  1759   |165      |2016-06-17 18:13:28
id1   |Primality|   242   |1        |2016-04-28 23:20:32 
id4   |Primality|    35   |2        |2016-05-02 21:37:07 

我做了这个查询来订购分数并将每个用户归为一个等级,例如对于游戏" Gravity" :

uuID | userName
id1  | Mathew
id2  | Jon

这是在几个论坛上发现的标准技术:我加入了一个临时表,其中包含一个用户定义的变量,该变量递增...并且只需加入用户表以获取友好名称。 请注意,我实际上使用2" rank"变量,因为我希望相同的分数具有相同的等级(并且具有不同数量的尝试的相同分数具有不同的等级) 结果没问题:

SELECT @rank:=@rank+1 rank,             
       IF(@score=s.score, @rank2:=@rank2, @rank2:=@rank) rank2, 
       s.uuID, 
       Users.userName, 
       @score:=s.score score, 
       s.attempt 
FROM 
       Scores s, 
       (SELECT @rank:=0, @score:=0, @rank2:=1) r, 
       Users 
WHERE   
       Users.uuID=s.uuID
       AND s.game='Gravity'
ORDER BY score DESC, attempt ASC

但是,如果我将此查询用作子查询,则结果完全是随机的:

rank |rank2  |uuID  |userName  |score |attempt   
1    |1      |id3   |Simon     |4910  |368 
2    |2      |id5   |youssef   |4284  |246 
3    |3      |id2   |Anonymous |2688  |97
4    |4      |id7   |Anonymous |2530  |12 
5    |5      |id8   |Anogjh    |2295  |24 
6    |5      |id9   |Nick      |2295  | 7

(XXX是之前的排名和排名2的选择) 给了我:

SELECT * FROM (XXX) temp

所以结果仍按分数和尝试顺序显示,但等级不再给出好结果。现在看来,升序排名遵循uuID升序的排序

请记住,我这样做是因为我的目标是查询等级为80到90的玩家:

rank  |rank2  |uuID  |userName  |score | attempt 
19    |19     |  id3 |Simon     |4910  |368 
28    |28     |  id5 |youssef   |4284  |246 
26    |26     |  id2 |Anonymous |2688  |97 
32    |32     |  id7 |Anonymous |2530  |12 

有人能解释一下子查询会发生什么吗? 也许有人有想法用另一种技术来获得我的结果?

编辑:我更正了说明中的userName列,我将准备一个sqlfiddle

0 个答案:

没有答案