Cross table constraints in PostgreSQL

前端 未结 3 1859
失恋的感觉
失恋的感觉 2020-12-21 15:58

Using PostgreSQL 9.2.4, I have a table users with a 1:many relation to the table user_roles. The users table stores both employees and

3条回答
  •  天涯浪人
    2020-12-21 16:19

    First, you can solve this using a trigger.

    But, I think you can solve this using constraints, with just a little weirdness:

    create table UserRoles (
        UserRoleId int not null primary key,
        . . .
        NeedsEmployeeNumber boolean not null,
        . . .
    );
    
    create table Users (
        . . .
        UserRoleId int,
        NeedsEmployeeNumber boolean,
        EmployeeNumber,
        foreign key (UserRoleId, NeedsEmployeeNumber) references UserRoles(UserRoleId, NeedsEmployeeNumber),
        check ((NeedsEmployeeNumber and EmployeeNumber is not null) or
               (not NeedsEmployeeNumber and EmployeeNumber is null)
              )
    );
    

    This should work, but it is an awkward solution:

    • When you add a role to an employee, you need to add the flag along with the role.
    • If a role is updated to change the flag, then this needs to be propagated to existing records -- and the propagation cannot be automatic because you also need to potentially set EmployeeNumber.

提交回复
热议问题