官网:https://dev.mysql.com/doc/refman/8.0/en/user-variables.html
可以查看具体定义,set @rank := 0;
按照这种规则就是定义变量@rank的值等于0;
变量的有效是在一次链接以内
基本就是这样使用,官网说了,有很多地方都可以使用计算
同样我有这几个表
score里面有userid和gameid以及gamescore
现在想按查询并按照gamescore排名
可能会这样写
set @rank := 0;
select @rank:= @rank+1 as userRank,user.username ,game.gamename,score.gamescore
FROM game,user,score
WHERE user.id = score.userid and game.id = score.gameid
ORDER BY gamescore
结果和想的不一样,那是因为select执行的时间在order by之前,排序的时候已经执行了。执行顺序可以看我我写的
所以想要排好就要最后再执行排序,所以你想到
set @rank := 0;
select @rank:= @rank+1 as userRank,t.*
FROM
(select user.username ,game.gamename,score.gamescore
FROM game,user,score
WHERE user.id = score.userid and game.id = score.gameid
ORDER BY gamescore )t
你发现,子查询了,不想这样,好像也可以: