I'm creating a really complex dynamic sql, it's got to return one row per user, but now I have to join against a one to many table. I do an outer join to make sure I get at least one row back (and can check for null to see if there's data in that table) but I have to make sure I only get one row back from this outer join part if there's multiple rows in this second table for this user. So far I've come up with this: (sybase)
select a.user_id from table1 a, table2 b where a.user_id = b.user_id and a.sub_id = (select min(c.sub_id) from table2 c where b.sub_id = c.sub_id)
The subquery finds the min value in the one to many table for that particular user.
This works but I fear nastiness from doing correlated subqueries when table 1 and 2 get very large. Is there a better way? I'm trying to dream up a way to get joins to do it, but I'm not seeing it. Also saying "where rowcount=1" or "top 1" doesn't help me, because I'm not trying to fix the above query, I'm ADDING the above to an already complex query.