在WHERE子句中使用ROW_NUMBER

时间:2017-09-20 05:23:15

标签: java sql derby

我正在尝试根据currentQuestion整数检索字符串值。但是我在文档中读到ROW_NUMBER不能在Java Derby的WHERE子句中使用。是否有其他可用的功能允许我根据行号过滤结果?到目前为止我已经写了这个,虽然我在getQuestion字符串上出错了。

public String getQuestion(int currentQuestion) throws SQLException {
        Statement statement = connection.createStatement();

        String getQuestion = ("SELECT QUESTION FROM GAME_TABLE WHERE ROW_NUMBER = ?");
        PreparedStatement preStatement = connection.prepareStatement(getQuestion);
        preStatement.setString(1, Integer.toString(currentQuestion));
        ResultSet resultSet = preStatement.executeQuery();

        System.out.println("Question " + Integer.toString(currentQuestion) + " retrieved.");

        return resultSet.getString(1);
    }

2 个答案:

答案 0 :(得分:0)

 Statement st = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
 String getQuestion = ("SELECT QUESTION FROM GAME_TABLE ");
 ResultSet resultSet = st.executeQuery(getQuestion);
 resultSet.absolute(currentQuestion);// moves the cursor to the row
 return resultSet.getString("Question");

当然,这个答案就像获得整个表格后的处理一样

答案 1 :(得分:0)

您可以使用CTE之类的:

WITH CTE As(
SELECT QUESTION, ROW_NUMBER() OVER (Arguments you want) As RN
FROM GAME_TABLE
)
SELECT *
FROM CTE
WHERE RN = ?;

或者,子查询如:

SELECT T.*
FROM ( SELECT QUESTION, ROW_NUMBER() OVER (Arguments you want) As RN
FROM GAME_TABLE ) As T
WHERE T.RN = ?;