- 查找由 「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);
}
}
關注:
- 上面的代碼將工作,我打算怎麼了它來說,但性能是一個主要因素。使用上面的代碼並不理想,因爲我們的「分數」表格將包含數十萬行。
我必須從這些結果中選擇以獲得特定用戶的排名嗎? 如果我將以下內容添加到該查詢: 其中s.user_id = 9017 等級是1,這是不正確的。 – Wonderlus
@Wonderlus。 。 。這實際上是一個非常不同的問題,請參閱編輯的回覆。 –