Bigserial ID番号は有用な目的ではありません。
create temp table my_table (
id integer not null,
version integer not null check(version > 0),
-- Give a lot of thought to whether text should also be unique. *I* think
-- it probably should, but it's really application-dependent.
text Text not null unique,
primary key (id, version)
);
insert into my_table values
(1, 1, 'My Text, first Version'),
(1, 2, 'My Text, second Version'),
(2, 1, 'My 2nd text v1'),
(2, 2, 'My 2nd text v2')
各IDのバージョン数。
select id, count(*)
from my_table
group by id;
各IDの最新バージョン。
with current_ver as (
select id, max(version) as version
from my_table
group by id
)
select m.* from my_table m
inner join current_ver c on c.id = m.id and c.version = m.version
私は共通のテーブル式でこれを書いていましたが、現在のバージョンのビューを作成することをお勧めします。私は、このデータにアクセスするほとんどのアプリケーションが最新のバージョンを必要とすると思います。
賢明な方法を助けるかもしれません。しかし私は自動増分(シリアル)のIDフィールドを逃す - トリガーではそれほど難しくない: CREATE SEQUENCE serial_my_table START 1; NEW.idがnullの場合 \t RETURNSが$$ \t AS \t \tをBEGINトリガ CREATE OR REPLACE FUNCTIONのins_my_table()THEN \t \t \t NEW.id:=のnextval( 'serial_my_table'); \t \t ELSE/*トリガーの後には良いかもしれないが、いくつかのクールなものを行う*/ \t \t END IF; \t \t RETURN NEW; \t END; \t $$言語 'plpgsql'; 存在する場合、ドロップトリガーtr_my_table_ins0 ON my_table; トリガーを作成するtr_my_table_ins0 \t前にmy_tableに挿入 \t各行の実行手順ins_my_table(); – Reinsbrain