簡體   English   中英

Postgresql 為插入/更新中的完整性約束創建觸發器

[英]Postgresql create trigger for integrity constraint in insert / update

我在 Postgresql 的數據庫中有這些表:

create table company (
  id bigint generated always as identity primary key,
  name text not null
);

create table employee (
  id bigint generated always as identity primary key,
  name text not null,
  company_id bigint not null references company(id)
);

create table manager_employee(
  id bigint generated always as identity primary key,
  manager_id bigint not null references employee(id),
  employee_id bigint not null references employee(id)
);
create unique index ux1_manager_employee on manager_employee(manager_id, employee_id);
alter table manager_employee add constraint ck1_manager_employee check (manager_id != employee_id);

我想確定當我在manager_employee表中插入/更新一個值時 manager_id 和 employee_id 屬於同一家公司,同一個company_id

我想我必須使用觸發器來確保這個條件,我該如何創建它?

謝謝

你可以用約束來做到這一點:

ALTER TABLE manager_employee ADD company_id bigint;

UPDATE manager_employee me
SET company_id = e.company_id
FROM employee e
WHERE me.employee_id = e.id;

ALTER TABLE manager_employee ALTER company_id SET NOT NULL;

ALTER TABLE employee ADD UNIQUE (company_id, id);

ALTER TABLE manager_employee ADD FOREIGN_KEY (company_id, manager_id)
   REFERENCES employee(company_id, id);

ALTER TABLE manager_employee ADD FOREIGN_KEY (company_id, employee_id)
   REFERENCES employee(company_id, id);

唯一約束與新列一樣冗余,但作為外鍵約束的目標是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM