Search code examples
javaresultset

How to compare the values of two resultset in java


I have two tables. And these tables have the same schema consisting of userid, username. I want to check is there any common username in table1 and table2.

 rs1 = statement.executeQuery("select username from table1")
 rs2 = statement.executeQuery("select username from table2")

My logic is:

  • while(rs1.next())
  • compare the value of rs1 with every value of rs2.
  • If there match found print one of the value else print both the values.

Is there a way to achieve this in java... Please anyone help me ... Thanks...


Solution

  • I would use a single SQL statement:

    select table1.username from table1, table2 where table1.username = table2.username
    

    This will only return usernames that appear in both tables, so no post-processing will be needed.

    This construct is called an inner join. If you also want to identify usernames that are unique to table1 and/or table2, you could use an outer join.