【问题标题】:Postgresql create trigger for integrity constraint in insert / updatePostgresql在插入/更新中为完整性约束创建触发器
【发布时间】:2021-02-03 20:22:30
【问题描述】:

我在 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

我想我必须使用触发器来确保这个条件,我该如何创建它?

谢谢

【问题讨论】:

    标签: sql postgresql triggers


    【解决方案1】:

    你可以通过约束来做到这一点:

    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);
    

    唯一约束与新列一样冗余,但作为外键约束的目标是必需的。

    【讨论】:

    • 我不明白 ALTER TABLE employee ADD UNIQUE (company_id, id); 中的 id 需要自动生成employee。你能解释一下吗?
    • 如果引用的列没有唯一约束,postgres 将引发错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多