Search code examples
javasqlsubqueryresultset

Use ResultSet for another query


I'd like to know if its possible to use a filled ResultSet in a second query. I'm thinking about something thats looking like a subquery.

SELECT t.id, t.name FROM table t, (
    SELECT * FROM table2
    )
t2
WHERE t.id = t2.id;

In SQL-Logic it would look something like this. I would like to use my ResultSet like the inner part of this query.


Solution

  • Since you only use id from your java resultset, you can loop on you resultset to fecth ids and concatene them within your query string, smth like:

    String query = "SELECT t.id, t.name FROM table t where t.id IN (";
    while(rs.next()) {
      query += rs.getInt("id") + ",";
    }
    query += ")";
    

    or better with a parametrized query