I have two tables, I’m given USERNAME:
User:
USERID
USERNAME
...other fields...
AccessRights (Many to One relationship with User.USERID):
USERID
GRANT
I want User.* fields, and all of the AccessRights where AccessRights.USERID=User.USERID
I can do this a few ways:
- Two separate queries, first for User, get the USERID and use that as a parameter in the 2nd query
- Join the tables, but this duplicates all of the User.* data over many rows
- Do some funky stored procedure to marshal the results into one field
But I have this gut feeling that I’m not thinking of some better approach, so I thought I’d ask.
Depending upon the database, you could also send a script in that outputs multiple resultsets. It also depends upon the language you’re coding in. But in Java, you can retrieve multiple resultsets from a query if you use Statement.execute (versus executeQuery).
This way, you can query from the User table first, then populate the user you’re looking for into a local variable, then use that variable to query the AccessRights table.
In all likelihood, unless you’re talking about a ton of rows in AccessRights or a ton of columns in User, it’s far simpler, and more efficient, to do a join. Just try to get only the fields from User that you need. The extra bytes of data moving across the wire is likely less overhead than multiple hits to the database to query each table individually (unless you use the approach above, which is one hit, but it’s probably overkill for most situations because it is a bit complex).