此查询:
SET @position := 0;
SELECT
(@position:=@position + 1),
(statistics.value - statistics_logs.value) AS value_new
FROM
rankings AS r
LEFT JOIN
rankings_logs AS rl ON statistics_logs.name = statistics.name
AND statistics_logs.user_id = statistics.user_id
ORDER BY value_new DESC
...没有给出预期的结果:
"(@position := @position + 1)" value_new
1 10
2 20
3 30
4 40
5 50
相反,它会返回奇怪的结果:
"(@position := @position + 1)" value_new
4 10
2 20
3 30
1 40
5 50
我认为这是因为value_new是从不同表中的两个值的抽象生成的,并且ORDER BY
在position
被定义之后以某种方式发生。但我不知道如何解决这个问题。有什么想法吗?
答案 0 :(得分:1)
我认为使用子查询会起作用:
SELECT (@position:=@position + 1), value_new
FROM (SELECT (statistics.value - statistics_logs.value) AS value_new
FROM rankings r LEFT JOIN
rankings_logs rl
ON rl.name = r.name AND sl.user_id = s.user_id
ORDER BY value_new DESC
) cross join
(select @position := 0) vars;