我有两个域实体:雇员和部门。 DDL看起来像这样:
CREATE TABLE department(
id SERIAL PRIMARY KEY
);
CREATE TABLE employee(
id SERIAL PRIMARY KEY,
department_id integer,
index_in_department integer
);
因此,主要字段是 index_in_department 。每个部门的数量都有独特的单调递增。
例如,我有2个部门和6名员工:
department - id == 1
department - id == 2
employee - id == 1, department_id == 1, index_in_department == 1
employee - id == 2, department_id == 1, index_in_department == 2
employee - id == 3, department_id == 1, index_in_department == 3
employee - id == 4, department_id == 2, index_in_department == 1
employee - id == 5, department_id == 2, index_in_department == 2
employee - id == 6, department_id == 2, index_in_department == 3
有什么方法可以在PostgreSQL中自动生成 index_in_department ?
由于多个线程并发插入,因此无法在应用程序级别上生成它。我知道,我可以使用数据库锁(例如咨询锁),但我想要更简单,更友好的解决方案。