【问题标题】:MySQL LIMIT with OFFSET not working as expected带有 OFFSET 的 MySQL LIMIT 未按预期工作
【发布时间】:2021-06-29 17:53:16
【问题描述】:

PreparedStatement ps 按预期工作,user_type 正在为第一行更新,但是我的第二条语句 (ps1) 应该更新第二行不是。因为唯一的变化是偏移量'LIMIT 1, 1;'我只能假设这就是系统抛出 MYSQLSyntaxErrorException 的原因。我是 MySQL 新手,所以不确定它为什么会抛出异常以及如何通过尝试其他方法来实现相同的目标。

try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/child_timer", "root", "");
    PreparedStatement ps = conn.prepareStatement("UPDATE user_profile SET user_type=? ORDER BY user_id ASC LIMIT 1;");
    ps.setString(1, sp.getUserType().name());
    int x = ps.executeUpdate();
    if (x > 0) {
        alertDialogBuilder(AlertType.INFORMATION, "Success", null, "Changes have been successfully saved.");
    } 
                
    PreparedStatement ps1 = conn.prepareStatement("UPDATE user_profile SET user_type=? ORDER BY user_id ASC LIMIT 1, 1;");
    ps1.setString(1, sp.getUserType1().name());
    int x1 = ps1.executeUpdate();
    if (x1 > 0) {
        alertDialogBuilder(AlertType.INFORMATION, "Success", null, "Changes have been successfully saved.");
    } catch (Exception e1) {
        System.out.println(e1);
    }   

【问题讨论】:

    标签: mysql sql-limit


    【解决方案1】:

    MySQL Update LIMIT 语句中没有偏移量。 提供一个最小 id 来创建偏移量,而不是像这样:

    wHERE user_id >= :offset
    

    【讨论】:

    • 这个问题是 user_id auto_increments 所以如果有 3 个 user_profile 和 user_id 1 被删除并创建一个新用户,新的 user_profile 将有 user_id 4 所以不能保证第二行会在该声明中更新。知道如何让新的 user_profile 的 user_id 填充尽可能低的 user_id 吗?
    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多