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?