簡體   English   中英

PostgreSQL獨占或列設置

[英]PostgreSQL exclusive or on column setting

在PostgreSQL 9.5中,我想創建一個包含三列的表。 我基本上會喜歡

create table Foo (
   account varchar not null,
   team_id integer references team (ident) on delete cascade,
   league_id integer references league (ident) on delete cascade
)

現在有趣的部分是我希望他們指定EITHER team_idleague_id ,但不能同時指定兩者。 然后, account加上其他兩列之一的組合就是UNIQUE約束。

那有可能嗎?

要確保僅提供一列,請使用檢查約束:

alter table foo add 
   constraint check_team check (not (team_id is not null and league_id is not null));

但是,以上內容不會阻止為列提供NULL值。 如果要確保提供其中之一,則可以使用:

alter table foo add 
   constraint check_team check ( (team_id is not null or league_id is not null) 
                                 and not (team_id is not null and league_id is not null));

編輯:正如Abelisto指出的那樣,可以將檢查約束簡化為

alter table foo add 
   constraint check_team check ((team_id is null) <> (league_id is null));

我不確定要建立的唯一約束。 如果例如應防止以下兩行('x', 1, null)('x', null, 1)則可以使用像這樣的唯一索引:

create unique index on foo (account, coalesce(team_id, league_id));

僅當您強制執行以下規則:至少其中一列必須不為null時,此方法才能正常工作。

但是,如果您想允許同一團隊進入不同的列,但又想防止一個帳戶兩次讓他擁有相同的team_id或League_id(允許上面的示例),那么我認為您需要唯一索引:

create unique index on foo (account, team_id) where team_id is not null; 
create unique index on foo (account, league_id) where league_id is not null; 

暫無
暫無

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

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