【发布时间】:2016-03-18 23:41:17
【问题描述】:
目标:
- 查找由“viewedUserId”标识的给定用户的排名
排名:
- 经验越高,等级越高(越低)。
- 如果两个或更多用户具有相同的体验,则更好的排名将授予首先获得该体验的人。 (updated_at 列存储 currentTimeMillis (bigint/long))
- 排名永远不应该打成平手。 (任何用户都不能拥有与其他用户相同的排名)
问题:
- 是否可以计算查询中的排名,这样我们就不必手动循环并比较每个存储的用户的结果。 (理想情况下,我们希望返回 1 个带有排名的结果)
代码:
public static int getRank(Connection connection, int viewedUserId) throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT user_id FROM scores ORDER BY experience DESC, updated_at ASC");
int rank = 1;
while(resultSet.next()) {
int userId = resultSet.getInt("user_id");
if(userId == viewedUserId)
return rank;
rank++;
}
throw new SQLException("Failed to find rank for user: " + viewedUserId);
} finally {
DatabaseUtils.close(statement, resultSet);
}
}
关注:
- 上面的代码将按照我的预期工作,但性能是一个主要因素。使用上述代码并不理想,因为我们的“分数”表将包含数十万行。
【问题讨论】: