我有两个SQL查询。但是在Java中,我无法设置变量。
我试图将其归纳为一个查询。但这不起作用,因为sql语法错误。
SET @rn = 0;
SELECT *
FROM (SELECT t.id, @rn := @rn + 1 AS rank
FROM stats t
ORDER BY t.points DESC) t2
WHERE t2.id = ?;
答案 0 :(得分:0)
如果只有SET部分是问题所在
SELECT t.id, @rn := @rn + 1 AS rank
FROM stats t
CROSS JOIN ( SELECT @rn := 0 ) as parameters
ORDER BY t.points DESC
答案 1 :(得分:0)
您需要像这样进行加入:
SELECT stats.id, @rn := @rn+1 AS rank
FROM stats, (SELECT @rn:=0) a
WHERE stats.id = ?
如果您拥有mysql 8.0,则可以使用: ROW_NUMBER() or RANK() :
SELECT
id,
ROW_NUMBER() OVER w AS 'row_number',
RANK() OVER w AS 'rank',
FROM stats
WHERE stats.id = ?
WINDOW w AS (ORDER BY points);