从MySQL Query中找到第一条正确记录后,Java ResultSet返回所有记录

时间:2014-12-01 19:38:29

标签: java mysql database sorting resultset

好的,例如我的表格如下:

┌──────┬────────┬─────────────┬───────────┐
│UserIDUsernameCurrentLeagueTotalPoints│
├──────┼────────┼─────────────┼───────────┤
│1     │Elliot  │randomLeague │15         │
├──────┼────────┼─────────────┼───────────┤
│2     │Callum  │randomLeague │20         │
├──────┼────────┼─────────────┼───────────┤
│3     │Rory    │testLeague   │17         │
├──────┼────────┼─────────────┼───────────┤
│4     │Admin   │NULL         │0          │
├──────┼────────┼─────────────┼───────────┤
│5     │Steve   │randomLeague │21         │
└──────┴────────┴─────────────┴───────────┘

这是我在我的Java项目中的代码,我正在这里使用。

public int getLeaguePosition(String username)
{
    try
    {
        int leaguePosition = 0;
        String leagueName = getLeague(username);
        System.out.println("League Name: " + leagueName);
        ArrayList<SortingUser> sortingUser = new ArrayList<SortingUser>();
        String query = "SELECT * FROM Users WHERE CurrentLeague = ?";
        preparedStatement = connection.prepareStatement(query);
        preparedStatement.setString(1, leagueName);
        resultSet = preparedStatement.executeQuery();
        while(resultSet.next())
        {
            String retrievedUsername = resultSet.getString("Username");
            System.out.println(retrievedUsername);
            SortingUser retrievedUser = new SortingUser(retrievedUsername);
            sortingUser.add(retrievedUser);
        }
        Collections.sort(sortingUser);
        for(int i = 0; i < sortingUser.size(); i++)
        {
            SortingUser retrievedSortingUser = sortingUser.get(i);
            String retrievedUsername = retrievedSortingUser.getUsername();
            if(retrievedUsername.contains(username) && username.contains(retrievedUsername))
            {
                leaguePosition = i + 1;
                System.out.println("League Position for " + username.toUpperCase() + " is " + leaguePosition);
                return leaguePosition;
            }
        }
    }
    catch(Exception e)
    {
        System.out.println("Couldn't get league position for: " + username);
        e.printStackTrace();
    }
    return 0;
}

如果我将“Rory”作为用户名,它将返回ID为3,4和5的记录,而不是在计算位置时返回3。

为什么这样做?我很确定我的代码是正确的,因为当我将那个确切的SQL查询复制到phpMyAdmin时,它可以很好地工作。

2 个答案:

答案 0 :(得分:0)

我不确定您使用SortingUser尝试做什么,但我会使用更简单的代码,并且让SQL自行排序。它通常非常有效,特别是如果你在桌面上有适当的索引。

public int getLeaguePosition(String username)
{
    try
    {
        String leagueName = getLeague(username);
        System.out.println("League Name: " + leagueName);

        // This is returning all the users in the same league sorted by descending points.

        String query = "SELECT * FROM Users WHERE CurrentLeague = ? ORDER BY TotalPoints DESC";
        preparedStatement = connection.prepareStatement(query);
        preparedStatement.setString(1, leagueName);
        resultSet = preparedStatement.executeQuery();

        int leaguePosition = 0;
        while(resultSet.next())
        {
            // Since the result set is already sorted, the first player has the most points, so his
            // leaguePosition is one. The second has the next best number of points, so his position
            // is two, and so on. So we keep the leaguePosition var based on the number of the row.

            leaguePosition++;

            // And if the user name retrieved actually matches the one that we passed, then this is
            // his league position.

            String retrievedUsername = resultSet.getString("Username");
            if ( retrievedUsername.equals( username ) ) {
                break;
            }

        }
        resultSet.close();

        return leaguePosition;

    }
    catch(Exception e)
    {
        System.out.println("Couldn't get league position for: " + username);
        e.printStackTrace();
    }
    return 0;
}

答案 1 :(得分:0)

您是否在 SortingUser 类中实施了Comparable界面?

如果您未在班级中实施Comparable,则Collections.sort()不会对对象进行排序。

简单示例检查this !!