我有一个第一个结果集,我必须在其中迭代userid,对于每个userid,我必须执行几个select count(*)'所有这些都返回单值输出。如果您还不了解我所说的内容,请按照以下伪代码进行操作:
ResultSet rs = stmt.executeQuery("select userid from tablename");
while(rs.next()){
String userid = rs.getString("userId");
ResultSet rs1 = stmt.executeQuery("select count(*) as cnt1 from xxx.... where userId = "+userId);
if(rs1.next())
String count1 = rs1.getString("cnt1");
rs1.close();
ResultSet rs2 = stmt.executeQuery("select count(*) as cnt2...");
if(rs2.next())
String count2 = rs2.getString("cnt2");
rs2.close();
....
rs10.close();
由于这是低效的,我希望每次都通过编写某种直接查询来检索每个不同的计数,例如
String cnt1 = stmt.executeQuery("select count(*) as noE from useractiontable where curr_action='edit'" + " and userId = " + userId).getString("noE");
我知道每次不使用rs.next()就无法完成这样的事情。是准备声明的方式去?还有另外一种方法吗?感谢这方面的任何指示。
答案 0 :(得分:2)
您可以使用group by
检索所有具有count(*)
ResultSet rs = stmt.executeQuery("select userid,count(*) from tablename group by userid");
答案 1 :(得分:0)
我怀疑你可以在一个查询中完成所有数据库工作,然后只需要读取一个结果集。它会更高效,代码更清晰。我想的是:
select userid, count(*) as cnt
from tablename t inner join othertablename ot on t.userid = ot.userid
group by userid
如果您在tablename
中有其他列,则可以将它们添加到select和group-by中。例如:
select userid, username, count(*) as cnt
from tablename t inner join othertablename ot on t.userid = ot.userid
group by userid, username
上述查询不会返回计数为零的用户ID。如果你想要零的那些,使用外连接(并使计数逻辑处理null的情况):
select userid, username, isnull(count(ot.userid), 0) as cnt
from tablename t left outer join othertablename ot on t.userid = ot.userid
group by userid, username