I have two tables that I join on the id-column, they look like:
+-------+
| users |
+----+--+---+
| id | name |
+----+------+
+-------+
| posts |
+-------+------+---------+
| id | user_id | message |
+----+---------+---------+
And now I want to select all posts and include the username, with:
SELECT * FROM posts, users WHERE user_id = users.id
And then I try to get the values with:
ResultSet rs = // SQL
if(rs.next()) {
rs.getInt("posts.id");
...
}
But I get SQLException when executing rs.getInt("posts.id") :
java.sql.SQLException: Column 'posts.id' not found.
How can I get the values from the SQL-query above using JDBC, and JavaDB/Derby as database?
How can I distinguish between the id column in the users and posts table when retrieving values with ResultSet?
You’re attempting to retrieve the
idvalue, but you’re using “posts.id” to reference it. Don’tAll you need is the column name or alias, not the table name as well:
It would’ve worked if your column name itself was “posts.id”, but I recommend using underscore (_) instead of a period should you choose to update the table.
But I have an id column in both tables, how do i distinguish between them?
You need to specify a column alias:
…and reference that column alias in the Java code: