I’ve have an sql database similar to the following:
Note: there is a missing column personId in event.
There are tables: Person that has many Events. Travel, playsBasquetBall and playsFooball are types of event.
How can I make a query that retunrs, for each person its current place (last travel event) and type of the last match (basquetball or football)?
Is theres somehow that I can do to skip the subqueries like the following (a part than denormalizing tables)?
SELECT person.*,
( SELECT place
FROM Travel
JOIN Event event ON place.id = event.id
AND event.personId = person.id
)
Example data:
Person(1)
Person(2)
Event(1, 20001001)
Travel(1, "Barcelona")
Event(2, 20011001)
Travel(2, "Paris")
Event(3, 2041001)
Travel(3, "Girona")
Event(4, 20001001)
Travel(4, "Barcelona")
Example response:
1, 4, Barcelona
2, null, null
2
Answers
This can be done using Multiple
LEFT JOIN
s :For this simple data :
Results :
Demo here
I believe you could use ’distinct on’ in a sub select left join.
Something like this
Would need to do similar for the sport event tables maybe using a ’union all’