This is related to Get records with max value for each group of grouped SQL results, except that the necessary groups are in a separate table.
Let's say that I have a couple of buildings, each building has some offices, and I have some people who "check in" to those offices to do work.
This table, called "offices", matches buildings to offices:
building office
---
Seuss Yertle
Seuss Cubbins
Milne Pooh
Milne Eeyore
Milne Roo
This table, called "checkins", records when people worked in each office:
id office person timestamp
---
1 Yertle Aaron 100
2 Cubbins Aaron 200
3 Pooh Aaron 300
4 Cubbins Charlie 300
5 Cubbins Aaron 700
6 Eeyore Beth 600
7 Pooh Beth 400
I'd like to generate a table that tells me, for each building-person combo, which check-in was the most recent one for that person in that building:
building person checkin_id office timestamp
---
Seuss Aaron 5 Cubbins 700
Milne Aaron 3 Pooh 300
Milne Beth 6 Eeyore 600
Seuss Charlie 4 Cubbins 300
I'm at a loss for how do I do this. The standard trick involves joining a table to itself while comparing the relevant value, then throwing away the rows where there is no bigger value. I assume I'll need two copies of "checkins" and two copies of "buildings" with a complex join between them, but I can't seem to get the NULLs to show up in the correct place.
I'm using MySQL, if that helps.