【问题标题】:Using ROW_NUMBER In WHERE Clause在 WHERE 子句中使用 ROW_NUMBER
【发布时间】:2017-09-20 05:23:15
【问题描述】:

我正在尝试根据 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);
    }

【问题讨论】:

  • 你得到什么错误?
  • 你可以使用CTE,或者子查询
  • java.sql.SQLSyntaxErrorException: Syntax error: Encountered "=" at line 1, column 50.

标签: java sql derby


【解决方案1】:
 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");

当然这个答案就像得到整个表格后的处理

【讨论】:

  • 您好,谢谢您,在线no suitable method found for createStatement(int) 出现错误。仅当我将 ResultSet.TYPE_SCROLL_SENSITIVE 添加到连接线时才会出现该错误。
  • 感谢编辑的代码,createConnection 方法不存在。我会尝试再搜索一下,谢谢:)
  • 对不起,你现在可以用更新的方式检查它吗.. 它会工作的
【解决方案2】:

您可以使用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 = ?;

【讨论】:

  • 谢谢,我试了一下,结果是java.sql.SQLException: Invalid cursor state - no current row。那是因为我在 Over() 函数参数中没有提供任何参数吗?
  • @TheChosenOne 你必须使用参数,比如OVER (order by ID ASC)
  • Derby 不支持公用表表达式,也不支持row_number() 中的order by
  • @a_horse_with_no_name 他可以使用子查询
猜你喜欢
  • 1970-01-01
  • 2010-11-30
  • 2010-10-24
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 2013-10-08
  • 2021-03-14
相关资源
最近更新 更多