繁体   English   中英

具有行版本控制的PostgreSQL数据库

[英]PostgreSQL database with row versioning

只是想从对StackOverflow社区说很多爱开始:)

所以我有一个Postgres数据库表,但让我们简化为重要的列:

id (string/int), when (timestamp/time/date), canonical (boolean)

在这种情况下, 规范表示“接受版本历史记录的一部分”。

假设我们的表格如下所示:

2, 2003-01-08, true
2, 2002-01-08, false
1, 2001-01-08, false
3, 2000-01-08, false
2, 2000-01-08, true
1, 2000-01-08, true
1, 1999-01-08, true

我想要一个查询,以查找每个ID最新规范版本 结果应如下所示:

2, 2003-01-08, true
1, 2000-01-08, true

所以我猜了两个问题:

  1. 您将如何为此编写查询?
  2. 可以索引吗?

一个更大的,更多的元问题是,是否存在一种更好的方法来存储此类信息。

select distinct on (id) *
from t
where canonical
order by id, "when" desc

此查询的最佳索引是部分索引

create index index_name on t (id, "when" desc) where canonical;

http://www.postgresql.org/docs/current/static/sql-createindex.html

select id, max("when")
from t
where canonical
group by id;

在某些情况下, 可能比不distinct on变体更快 ,并且您不需要按id对结果进行排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM