Sql 实际/历史表:按版本号选择

Sql 实际/历史表:按版本号选择,sql,postgresql,database-versioning,Sql,Postgresql,Database Versioning,我在PostgresSQL数据库中有两个DB表: create table actual (id int, name text, version int) create table history (id int, name text, version int, actual_id int) 当记录更改时,会将其复制到历史记录表中,并且实际版本会增加。无法删除行 例如,如果我们有3条记录A1、B1、C1 1是版本号并更改了B的名称,那么实际的表将包含A1、B2、C1和历史-B1。然后,我们可以

我在PostgresSQL数据库中有两个DB表:

create table actual (id int, name text, version int)
create table history (id int, name text, version int, actual_id int)
当记录更改时,会将其复制到历史记录表中,并且实际版本会增加。无法删除行

例如,如果我们有3条记录A1、B1、C1 1是版本号并更改了B的名称,那么实际的表将包含A1、B2、C1和历史-B1。然后,我们可以更改C的名称,实际数据将是A1、B2、C3和历史-B1、C1

如何按名称和版本号选择行?例如,version=2和名称“%”应该为我们提供A1、B2、C1 A1和C1在版本2上仍然是实际的,它们与版本1没有变化

我提出了一个工会选择,例如:

select id, name, version from 
(
    select id, name, version, id as actual_id from actual 
    union select id, name, version, actual_id from history
) q
where version <= 2 and name like '%'
group by actual_id
order by version desc;

有没有可能在没有联合的情况下做到这一点,即Hibernate不支持它或使用某种更优化的方法?

解决这一问题的明智方法是将实际行也放在历史记录表中。然后,当需要所有历史记录时,只需查看历史记录,而当需要对当前项进行fadt查找时,可以查看实际情况


或者将实际的表全部废弃。不过,这是一个体系结构设计。

解决这个问题的聪明方法是将实际行也放入历史表中。然后,当需要所有历史记录时,只需查看历史记录,而当需要对当前项进行fadt查找时,可以查看实际情况


或者将实际的表全部废弃。不过,这是一个架构设计。

我不确定OP的db供应商是什么。但是,以下内容适用于MS SQL:

select * from (
select row_number() over (partition by id order by version desc) rn, 
       name 
from 
(
  select h.actual_id as id, h.name, h.version from history h
  union all
  select * from actual 
) x
where version <= 2 )  y
where rn = 1

我不确定OP的db供应商是什么。但是,以下内容适用于MS SQL:

select * from (
select row_number() over (partition by id order by version desc) rn, 
       name 
from 
(
  select h.actual_id as id, h.name, h.version from history h
  union all
  select * from actual 
) x
where version <= 2 )  y
where rn = 1

感谢您指出DB供应商的问题。它是PostgreSQL数据库。添加到问题中。感谢您指出DB供应商。它是PostgreSQL数据库。我认为这是最好的解决方案,但你是对的——我不能改变架构。我认为这是最好的解决方案,但你是对的——我不能改变架构。