In a postgresql database I have 2 tables like these ones:
Table items:
item_id item save_date (date dd/mm/yy)
----------------------------------------------
1 car 01/12/11
2 wheel 10/12/11
3 screen 11/12/11
4 table 15/12/11
Table periods:
period_id period_name start (date dd/mm/yy)
------------------------------------------------
1 period1 05/12/11
2 period2 09/12/11
3 period3 12/12/11
So I would like to get a joined table adding to the table items the most suitable period (if on matches). A period will match if the save_date of the item is after the start date of the period.
For example for “car” the date is 01/12/2011 so I go to the table periods and there I can see that all periods start after that date, so I have to set it to null. If I take “screen” the date is 11/12/11 so in the periods I should take period2, because it’s the latest which matches.
So the joined table would result in:
item_id item save_date period_name
----------------------------------------------
1 car 01/12/11 null
2 wheel 10/12/11 period2
3 screen 11/12/11 period2
4 table 15/12/11 period3
What is the best way to do this join?
Thanks
The result: