【问题标题】:Building Select Query Using IN(...) Clause使用 IN(...) 子句构建选择查询
【发布时间】:2011-09-11 08:17:42
【问题描述】:

我需要根据输入 ID 列表进行选择 *,批量选择的最佳方式是什么?这就是我所拥有的

StringBuilder inClause = new StringBuilder(); boolean firstValue = true; for (int i=0; i

【问题讨论】:

    标签: java mysql sql select jdbc


    【解决方案1】:

    对我来说看起来不错。刚刚在这段代码中发现了一个逻辑错误,

    boolean firstValue = true;
    for (int i=0; i < batchSize; i++) {
      inClause.append('?');
      if ( firstValue ) {
        firstValue = false;
      } else {
        inClause.append(',');
      }
    }
    

    它不会在第一个元素之后附加,。最后一个之后会有一个,。所以,你不必在这里关心,。就这样做吧

    for (int i=0; i < batchSize; i++) {
      inClause.append('?, ');
    }
    

    然后像这样砍掉最后两个字符,

    PreparedStatement stmt = conn.prepareStatement(
        "select id, name from users where id in (" + 
        inClause.substring(0, inClause.length()-2) + ')');
    

    【讨论】:

    • 这是最快的方法吗?
    • @user775187:如果id是唯一的,并且需要根据多个ids查询记录——如果没有其他选项,那么IN(...)是方法。因此,您必须使用这种或类似的技术来构建您的查询。
    猜你喜欢
    • 2012-05-30
    • 2019-09-05
    • 1970-01-01
    • 2011-04-18
    • 2013-07-26
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 2018-11-21
    相关资源
    最近更新 更多