我有一个像这样的RANK
表
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| uid | VARCHAR(50) unsigned | NO | PRI | NULL | |
| steps | int(20) unsigned | NO | | NULL | |
+-------------+---------------------+------+-----+---------+----------------+
我希望通过DESC对步骤进行排序,并使用主要的uid获取特定行的行位置。
我可以按
排序 SELECT uid, steps FROM RANK ORDER BY steps DESC
但我不知道如何使用uid获取特定行的行位置。我在stackoverflow上看到了一些线程,并在我们的数据库服务器上尝试了它,但它没有成功。有没有办法做到这一点?
我试过了:
SET @rank=0;
SELECT @rank:=@rank+1 AS rank, steps, COUNT(*) as ordercount
FROM RANK
GROUP BY steps
ORDER BY ordercount DESC;
但它没有得到我的任何结果
async function getUserData(uid) {
var query = ""
query += "SELECT rank, total_steps_value FROM ("
query += " SELECT @rank := @rank + 1 AS rank, user_id, total_steps_value"
query += " FROM RANK"
query += " CROSS JOIN (SELECT @rank := 0) AS var"
query += " ORDER BY total_steps_value DESC) AS x"
query += `WHERE user_id = ${mysql.escape(uid)}`
let res = await models.sequelize.query(query)
console.log("RES", res)
}
我收到此错误
SequelizeDatabaseError: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_id = '10208360871964156'' at line 1
答案 0 :(得分:2)
您不需要COUNT(*)
,因为您没有尝试按计数排名,您只想按列值进行排名。
SELECT @rank := @rank + 1 AS rank, uid
FROM RANK
CROSS JOIN (SELECT @rank := 0) AS var
ORDER BY steps DESC
要获取特定uid
的排名,请将其放在子查询中。
SELECT rank FROM (
SELECT @rank := @rank + 1 AS rank, uid
FROM RANK
CROSS JOIN (SELECT @rank := 0) AS var
ORDER BY steps DESC) AS x
WHERE uid = '123545'
答案 1 :(得分:0)
您还可以使用以下方式获取特定行的排名:
select count(*)
from rank r
where r.score >= (select r2.score from rank r2 where r2.uid = ?);