的BIGSERIAL身份證號碼沒有用處。
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; CREATE OR REPLACE FUNCTION ins_my_table() \t RETURNS觸發AS $$ \t BEGIN \t \t IF NEW.id IS NULL THEN \t \t \t NEW.id:= NEXTVAL( 'serial_my_table'); \t \t ELSE/*做一些很酷的東西,雖然可能會更好,因爲後觸發*/ \t \t END IF; \t \t RETURN NEW; \t END; \t $$ language'plpgsql'; DROP TRIGGER IF EXISTS tr_my_table_ins0 ON my_table; CREATE TRIGGER tr_my_table_ins0 \t插入之前my_table \t FOR EACH ROW EXECUTE PROCEDURE ins_my_table(); – Reinsbrain 2016-05-05 23:01:45