时间轴数据库架构?

时间:2014-08-04 18:41:29

标签: sql database-design

我无法为时间线找到一个好的数据库结构/架构。

我有一个用户可以创建多种类型对象的站点,这些对象具有许多不同的属性,因此保存在许多不同的表中。

我的时间轴会显示按日期排序的所有不同对象。

我的想法是在创建新对象时在我的时间轴表中插入记录:

insert into timeline (date, objectType, objectId) values (...)

要显示我的时间表,我会这样做:

select * from timeline order by date desc limit 100

这里没问题。接下来我需要获取将在时间轴上显示的对象数据,只需:

select * from objectType where id = objectId 

我的时间轴中的每个条目。这将成为问题,这些是许多查询的方式。

当然,我可以通过以下方式对其进行微调:

select * from objectType where id in (objectId, objectId)

但是当我的时间轴中有很多objectTypes时,它仍然是很多查询。

任何人对更好的方法都有一个好主意吗?

1 个答案:

答案 0 :(得分:2)

您不会说出您正在使用的SQL风格,因此很难说出要回答的语法类型。这里有一些伪代码可以给你一个想法:

创建一个临时表(或视图),使用UNION连接不同类型的可显示详细信息,然后从中选择TOP / LIMIT。

您可以将时间轴连接到各种对象类型,根据转换每种对象类型中的本机列,将每种对象类型的属性投影为一致的可显示格式:

CREATE VIEW displayable_events
AS
select 
  e.date, e.objectType, e.objectID, 
  o.ColumnOfInterest1 + '-' + o.ColumnOfInterest2 as Description
                      -- Or whatever you want to show
from timeline e 
  inner join objectTypeA o
    on e.objectID = o.objectID
where e.objectType = 'TypeA' -- or whatever you're using to distinguish them.
--
UNION ALL
--
select 
  e.date, e.objectType, e.objectID, 
  o.ColumnOfInterest1 + 'anything else you like' as Description
from timeline e 
  inner join objectTypeB o
    on e.objectID = o.objectID
where e.objectType = 'TypeB' 
--
UNION ALL
--
... and so forth for all of your object types...

然后你可以从这个视图(或临时表)中选择如下:

SELECT * from displayable_events
WHERE -- whatever you use to distinguish whose timeline you want ---
ORDER BY date DESC
LIMIT 100

这可以节省您为每个时间轴条目单独执行所有查询,因为它使用基于集合的方法。