复合键每组行的序列号

问题描述 投票:8回答:1

我正在尝试维护地址历史记录表:

CREATE TABLE address_history (
    person_id int, 
    sequence int,
    timestamp datetime default current_timestamp,
    address text,
    original_address text,
    previous_address text,
    PRIMARY KEY(person_id, sequence),
    FOREIGN KEY(person_id) REFERENCES people.id
);

我想知道是否有一种简单的方法可以自动编号/约束sequence中的address_history以自动从每个person_id的1开始计数。

换句话说,具有person_id = 1的第一行将得到sequence = 1person_id = 1的第二行将得到sequence = 2。具有person_id = 2的第一行将再次获得sequence = 1。等等。另外,是否有更好/内置的方式来维护这样的历史记录?

sql postgresql database-design auto-increment
1个回答
20
投票
使用普通的serialIDENTITY列:

Auto increment table column

    CREATE TABLE address_history ( address_history_id serial PRIMARY KEY , person_id int NOT NULL REFERENCES people(id) , created_at timestamp NOT NULL DEFAULT current_timestamp , previous_address text );
  • 使用窗口功能row_number()获取没有序列号的序列号person_id。您可以将VIEW保留为查询中的表的替代品,以准备好这些数字:
    VIEW

    参见:

    CREATE VIEW address_history_nr AS SELECT *, row_number() OVER (PARTITION BY person_id ORDER BY address_history_id) AS adr_nr FROM address_history;

© www.soinside.com 2019 - 2024. All rights reserved.