Your example may be too simplistic, but I would use a group:
SELECT
a.user_id
FROM
table1 a
LEFT OUTER JOIN table2 b ON (a.user_id = b.user_id)
GROUP BY
a.user_id
I am afraid that the only way would be to use nested queries:
The difference between this query and your example is a “helper table” that is generated only once, however in your example you create a “helper table” for each row in table1 (but it may depend on the compiler, so you might want to use a query analyzer for performance checks).
SELECT
a.user_id,
b.sub_id
FROM
table1 a
LEFT OUTER JOIN (
SELECT
user_id
min (sub_id) as sub_id,
FROM
table2
GROUP BY
user_id
) b ON (a.user_id = b.user_id)
Also, if your query becomes quite complex, I would use temporary tables to simplify the code, it may cost a little more during processing, but it will simplify your queries.
Example Temp Table:
SELECT
user_id
INTO
# table1
FROM
table1
WHERE
.....
SELECT
a.user_id,
min (b.sub_id) as sub_id,
INTO
# table2
FROM
# table1 a
INNER JOIN table2 b ON (a.user_id = b.user_id)
GROUP BY
a.user_id
SELECT
a. *,
b.sub_id
from
# table1 a
LEFT OUTER JOIN # table2 b ON (a.user_id = b.user_id)
source share