我有两个 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 = ?;
我有两个 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 = ?;
如果只有 SET 部分是你可以做的问题
SELECT t.id, @rn := @rn + 1 AS rank
FROM stats t
CROSS JOIN ( SELECT @rn := 0 ) as parameters
ORDER BY t.points DESC
你需要像这样加入:
SELECT stats.id, @rn := @rn+1 AS rank
FROM stats, (SELECT @rn:=0) a
WHERE stats.id = ?
如果你有 mysql 8.0,你可以使用:ROW_NUMBER() 或 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);