PostgreSQL - Foreign Key References Mutually Exclusive Tables

前端 未结 1 999
孤独总比滥情好
孤独总比滥情好 2021-01-12 19:57

I have three database tables: ALIENS, MONSTERS, and TROPHIES.

Each ALIEN can have multiple TROPHIES. Each MONSTER can have multiple TROPHIES. Each TROPHY must have e

相关标签:
1条回答
  • 2021-01-12 21:00

    You could create two foreign keys with a check constraint that says exactly one is empty:

    create table alien (id int primary key);
    create table monster (id int primary key);
    create table trophy (id int primary key,
        alien_id int references alien(id),
        monster_id int references monster(id),
        check (alien_id is null <> monster_id is null)
    );
    
    0 讨论(0)
提交回复
热议问题