在我的数据库中,我有一个配置文件表,其中包括以下列:
Id
, profilename
,points
,lastupdated
可以多次将用户放入配置文件表中,对于排行榜,我使用 max(lastupdated
) 列的值。
下面我有 SQL 代码来尝试确定某人的排行榜位置,除了 1 个小问题外,它工作正常。
SELECT COUNT( DISTINCT `profilename` )
FROM `profiletable`
WHERE `points` >= integer
如果两个人的积分相同,那么他们在排行榜上的位置也相同,但这会使计数功能以我不希望的方式工作。
例如:
position 1: profilename john points 500
position 2: profilename steve points 300
position 2: profilename alice points 300
position 4: profilename ben points 200
当我在将 Integer 设置为 john's points 的情况下运行 SQL 查询时,我从计数函数中得到返回值 1,但是当我为 steve 或 alice 运行 SQL 查询时,我得到的不是 2,而是 3。
我也尝试过使用逻辑 points > integer
但是这会为 steve 或 alice 返回 1。
如何修改 SQL 查询,以便计数返回正确的排行榜位置?
最佳答案
在 where 子句中使用大于号并将计数加 1:
SELECT COUNT( DISTINCT `profilename` ) + 1
FROM `profiletable`
WHERE `points` > integer
更新:
如果你还需要考虑更新时间字段,那么首先你需要获取与最后更新时间相关联的记录:
SELECT COUNT(p1.`profilename` ) + 1
FROM `profiletable` p1
LEFT JOIN `profiletable` p2 ON p1.profilename=p2.profilename
and p1.lastupdated<p2.lastupdated
WHERE p1.`points` > integer and p2.profilename is null
关于php - 如何根据用户使用 SQL 获得的积分数量找到用户的排行榜位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48719207/