基本上,我有一个循环(在java中),它从表中查找每个id并用它做一些事情。在每个循环中,它与数据库交互几次。它的执行速度比我想要的慢,所以我记录了与DB的每次交互。我发现下面这个sql比其他sqls花了更多的时间。
select id from (select id,rownum as rn from person_info) where rn=#{rowNum}
这是循环的开始,我需要在执行其他操作之前先获取id。我在这里使用rownum因为我想一次读一行。为了您的信息,我一次做一行,因为它涉及几个表,每个表有数十亿行,如果我加入它们或运行复杂的sqls,它需要永远。底线是我需要保持sql尽可能简单。
然而,这一行需要比其他sqls执行更长的时间。我认为这是由于rownum的性质,因为它查看了整个表格。有可能优化这个SQL甚至不使用rownum?
id
是主要关键。如果您需要更多信息,请随时提出!
编辑:这是代码
for(int i = 1; i<=count; i++){
long startTime=System.currentTimeMillis();
String pid = ns.findPId(i); //find one pid at a time, average execution time ~130ms
//sql: select id from (select id,rownum as rn from person_info) where rn=#{rowNum}
long endTime=System.currentTimeMillis();
log.info("findPId(i): "+(endTime - startTime)+"ms");
startTime=System.currentTimeMillis();
Genotype g = ns.findPersonInfo(pid); //obtain associated info, average execution time ~20ms
endTime=System.currentTimeMillis();
log.info("findPersonInfo(pid): "+(endTime - startTime)+"ms");
if(g!=null){
if(g.getIdCardNumber()!=null && g.getIdCardNumber().matches(idCardNoEL)){ //valid card number
startTime=System.currentTimeMillis();
int isMatch = findPersonIdNoMatch(pid); //average execution time ~2ms
endTime=System.currentTimeMillis();
log.info("findPersonIdNoMatch(pid): "+(endTime - startTime)+"ms");
if(isMatch == 0){
startTime=System.currentTimeMillis();
String sampleId = ns.findSampleIdByPid(pid); //average execution ~10ms
endTime=System.currentTimeMillis();
log.info("findSampleIdByPid(pid): "+(endTime - startTime)+"ms");
if(sampleId!=null){
startTime=System.currentTimeMillis();
Genotype temp = ns.findGeneInfoBySampleId(sampleId); //get geneinfo and createDateTime, average execution ~10ms
endTime=System.currentTimeMillis();
log.info("findGeneInfoBySampleId(sampleId): "+(endTime - startTime)+"ms");
if(temp!=null){
startTime=System.currentTimeMillis();
g.setGeneInfo(temp.getGeneInfo());
g.setCreateDateTime(temp.getCreateDateTime());
endTime=System.currentTimeMillis();
log.info("set: "+(endTime - startTime)+"ms");
startTime=System.currentTimeMillis();
insertGenotype(g); //average execution 1ms
endTime=System.currentTimeMillis();
log.info("insertGenotype(g): "+(endTime - startTime)+"ms");
}
}
}else{
//log
}
}
}
您可能更喜欢运行简单的查询
select id,rownum as rn from person_info
并从你的java代码迭代它。不要一次得到所有结果,而是一次得到一行。你会在这里找到更多信息:https://dzone.com/articles/the-performance-difference-between-sql-row-by-row