先试试这个(示例用于 PostgeSQL)。
-- Latest location of ItemID = 75
select
a.ItemID
, b.LocationID
, ValidFrom
from Item as a
join ItemLocation as b on b.ItemID = a.ItemID
and b.ValidFrom = (select max(x.ValidFrom) from ItemLocation as x
where x.ItemID = a.ItemID)
join Location as c on b.LocationID = c.LocationID
where a.ItemID = 75 ;
-- Earliest location of ItemID = 75
select
a.ItemID
, b.LocationID
, ValidFrom
from Item as a
join ItemLocation as b on b.ItemID = a.ItemID
and b.ValidFrom = (select min(x.ValidFrom) from ItemLocation as x
where x.ItemID = a.ItemID)
join Location as c on b.LocationID = c.LocationID
where a.ItemID = 75 ;
这可能看起来很吓人,但速度很快,ItemID
是主键的一部分
如果您需要在任何时间点列出所有项目
-- Location of all items for point in time ('2012-05-01 11:00:00')
select
a.ItemID
, b.LocationID
, ValidFrom
from Item as a
join ItemLocation as b on b.ItemID = a.ItemID
and b.ValidFrom = (select max(x.ValidFrom)
from ItemLocation as x
where x.ItemID = a.ItemID
and x.ValidFrom <= '2012-05-01 11:00:00')
join Location as c on c.LocationID = b.LocationID
;