问题所在
使用单个查询,我希望能够在我的数据库表中找到一行,并生成一个虚拟列,该列表示该列的“级别”,这是基于它在排序另一列时所处的位置。
假设我把这个表放在一个mySQL DB中:
id | score
1 | 400
2 | 700
3 | 200
4 | 800
现在我想用3的id来查找这一行,并根据分数计算出这一行的排名。
显然,在表中,如果将秩从最高分分配到最低,那么第3行将得到4的等级,因为它在表中的4行中得分最低。在本例中,我不想对findAll
进行排序,因为我的真实表非常大。
我试过的
Model.findOne({
attributes: [
'id',
'score',
sequelize.literal('RANK() OVER (ORDER BY score DESC) rank')
]
});
这给了我一个错误:
"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 '(ORDER BY score DESC) rank FROM `Model` AS `Model` LIMIT 1' at line 1",
我非常感谢任何解决方案/建议!
编辑:版本- mySQL 5.6,续订4.35.2
发布于 2020-02-12 23:31:08
你的意思是这样的:
SELECT * FROM (
SELECT id, score, rank from
(
SELECT id, score, @tmprank := @tmprank + 1 AS rank
FROM scores
CROSS JOIN (SELECT @tmprank := 0) init
ORDER BY score DESC
) rt
ORDER BY rank
) AS r
WHERE r.id = 3;
样本
mysql> select * from scores;
+----+-------+
| id | score |
+----+-------+
| 1 | 400 |
| 2 | 700 |
| 3 | 200 |
| 4 | 800 |
+----+-------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM (
-> SELECT id, score, rank from
-> (
-> SELECT id, score, @tmprank := @tmprank + 1 AS rank
-> FROM scores
-> CROSS JOIN (SELECT @tmprank := 0) init
-> ORDER BY score DESC
-> ) rt
-> ORDER BY rank
-> ) AS r
-> WHERE r.id = 3
-> ;
+----+-------+------+
| id | score | rank |
+----+-------+------+
| 3 | 200 | 4 |
+----+-------+------+
1 row in set (0.00 sec)
mysql>
发布于 2021-06-27 10:23:58
我通过计数"object“上面的对象来解决这个问题,我正在寻找一个级别。
const rank = await Game.count({
where: {
score: {
[Op.gt]: game.score // Op.gt it is syntax for grather then
},
}
})
rank++; // you have to add 1 to have the correct number
这不是最有效的方法,但有效。
下面是Sequelizer的另一个操作符:https://sequelizedocs.fullstackacademy.com/search-operators/
玩得开心
发布于 2022-02-22 10:04:47
我找到了一个解决方案,您的方法很好,只是语法错误,请找到正确的语法
Model.findOne({
attributes: [
'id',
'score',
[sequelize.literal('RANK() OVER (ORDER BY "score" DESC)'), 'rank']
]});
https://stackoverflow.com/questions/60198208
复制相似问题