java nested while loop in result set

醉酒当歌 提交于 2019-12-11 12:46:39

问题


I want to merge results from 2 resultSet which are results returned from sql queries. What is the best way to accomplish this?

My plan is lopping over 2 result sets to print out the final result from both result sets. Both results set have the same id column which are their first column. But for the inner while loop, I only get the first value printed out.

I thought when there is a match, it prints the value from the second result set, and break out of the loop. Then when there is another match, it prints out the value again.

while (set1.next())
{
    System.out.print("Id: "+set1.getInt(1)+", Name: "+set1.getString(2));

    while (set2.next())
    {
        if (set1.getInt(1)==(set2.getInt(1)))
        {  
            System.out.print(", Alias: "+set2.getString(2);
            break;
        }
    }

    System.out.println();
}

Edit:

ResultSet set1: 
id | name
1  | A
2  | B
3  | C
...

ResultSet set2:
id | alias
1  | F
2  | G
2  | H

I want to print out:

Id: 1, Name: A, Alias: F
Id: 2, Name: B, Alias: G, H

FYI, the id is in ascending orders in both sets


回答1:


Since the two result sets have the same first column (id), you can start from the first row for both result sets. In the inner loop, iterate over the rows in set2 until its id is great than the id in set1. So you can do:

while (set1.next())
{
    System.out.print("Id: "+set1.getInt(1)+", Name: "+set1.getString(2));

    while (set2.next())
    {
        System.out.print(", Alias:");
        if (set1.getInt(1)==(set2.getInt(1)))
        {  
            System.out.print(set2.getString(2) + ", ");
            continue;
        } else {
            set2.previous();
            break;
        }
    }
    System.out.println();
}



回答2:


The below loop will only executed once for the outer loop

        while (set2.next()){
            if (set1.getInt(1)==(set2.getInt(1))){  
                System.out.print(", Alias: "+set2.getString(2);
                break;
            }
        }

You need to reinitialize your iterator each time the outer loop executes.



来源:https://stackoverflow.com/questions/22239423/java-nested-while-loop-in-result-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!