I have a query that selects a set of Users. Each User can have a number
of Events associated with it. I want to join each User with the earliest Event
associated with that User (resulting in one row per User), and do so within a single query.
So, I kind of want to do this:
SELECT * FROM users
left join (
select * from events where events.user_id = users.id
order by start_time limit 1) as event
ON ("event"."user_id" = "users"."id")
but it is illegal to reference ‘users’ within the join’s select.
You can use a subquery to get the
min(start_time)for eachuser_id. Then you will use this result to join back to theeventstable to get the details of the min event:If you are using a database that has the ability to apply a
row_number(), then you could use the following: