我对你想要达到的目标有点困惑,但我想你需要这个:
select * from city as c inner join user as u on (c.ID = u.city_ID)
where u.name = ?;
然后你只需要执行这一个查询,你就会得到想要的结果。
但也正如@dystroy 提到的,如果您想使用您的方法,您首先需要从 User 获取 id 到 some中List<Integer>
,然后创建一些List<String>
将在您的查询中保存您的查询或 useIN
子句的方法。
伪代码:
// getting ids from User
List<Integer> cityIds = new ArrayList<Integer>();
String query = "select city_ID from user where name = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
cityIds.add(rs.getInt("city_ID"));
}
// dynamically create your query
StringBuilder builder = new StringBuilder("select * from city where ID in (");
for (int i = 0; i < cityIds.size(); i++) {
builder.append("?");
if (i < cityIds.size() - 1) {
builder.append(",");
}
}
builder.append(")");
// creating PreparedStatement
ps = con.prepareStatement(builder.toString());
// adding params to query
int index = 1;
for (Integer id: cityIds) {
ps.setInt(index, id);
index++;
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// do your stuff
}
注意:我建议您使用参数化的语句,这样可以更安全地处理数据库,更易于阅读和更高效。