I have a table relationship that looks like the following:
barn
------
PK barn_id
<other columns>
stable
---------
PK stable_id
FK barn_id
stable_number
stable_contents
timestamp
So whenever the contents of a stable change I just put in a new row with the corresponding barn_id and stable_number with new stable_contents and a current timestamp.
The tables are designed this way so I can look at a certain stable and see its entire history.
I am trying to write a query that will find me the current state of all the stables in all the barns, so I try this:
SELECT barn_id, stable_number, max(timestamp), stable_contents
FROM stable
GROUP BY barn_id, stable_number
In my test data I have some rows like this for barn 1, stable 7
1 | 7 | 2009-12-09 10:00:00 | empty
1 | 7 | 2009-12-10 10:30:00 | show horse
If I run the SELECT query above, I get the following row returned for barn 1, stable 7:
1 | 7 | 2009-12-10 10:30:00 | empty
it gets the right maximum timestamp, just the wrong stable_contents.
Any ideas?
It really should give you an error instead of returning undefined data because you’re trying to get non-aggregated data that isn’t in your GROUP BY (stable_contents). I would use the following query, which finds all rows for a stable where there isn’t a row after it for the same stable:
Alternatively: