Mysql在一个查询中选择并更新列

时间:2015-03-24 15:48:24

标签: java mysql

是否可以将以下查询合并为一个?我使用mysql作为我的数据库。

String qry = "SELECT id FROM customers WHERE completed=false AND server=?";
ps = connection.prepareStatement(qry);
ps.setString(1,getServerId());
rs = ps.executeQuery();
final Set<Long> ids = new HashSet<>();
while (rs.next()) {
    ids.add(rs.getLong(1));
}
qry = "";
for (long l : ids) {
     qry += "UPDATE customers SET completed=true WHERE id = "+l+"; ";
}

...执行查询,关闭流,并使用数据库中的ID执行一些应用程序逻辑...

1 个答案:

答案 0 :(得分:2)

你可以

UPDATE customers SET completed=true WHERE completed=false AND server=?

编辑:您提供了说明您需要实际使用ID的信息。 正常选择然后以MySql理解为“列表”的格式构建字符串,它肯定比多个更新查询更快,并且通过网络发送的字节数更少。这是片段:

String qry = "SELECT id FROM customers WHERE completed=false AND server=?";
ps = connection.prepareStatement(qry);
ps.setString(1,getServerId());
rs = ps.executeQuery();
final Set<Long> ids = new HashSet<>();
while (rs.next()) {
    ids.add(rs.getLong(1));
}
qry = "";
if(ids.size()>0) {
    StringBuilder idsAsString = new StringBuilder();
    for(int i = 0; i < ids.size(); i++) {
        idsAsString.append(ids.get(i));
        if(i < ids.size()-1)
            idsAsString.append(",");
    }
    qry = "UPDATE customers SET completed=true WHERE id IN ("+idsAsString+"); ";
}

而不是在for循环中构建多个UPDATE语句。