[英]How to constrain two columns in SQL to have a value in one column only be allowed to appear in combination with the value in the other column?
[英]PostgresQL: Value is only allowed in one of two columns
我有一個包含兩個表“Config”和“Config_xml”的數據庫,每個表都包含相同的列(id、content、modifier 等)。 唯一的區別是,該配置在其內容列中僅包含非 xml 字符串,而 config_xml 在其內容列中包含 xml 字符串。
現在我想將這兩個表合並為一個,提供一個內容列和一個 xml_content 列,以簡化查詢,因為目前我總是要在兩個表上進行查詢。
現在有沒有辦法限制每一行以允許內容或xml_content 中的值?
提前致謝。
您可以使用要求一列為 null 的檢查約束。
alter table the_table
add constraint check_content
check (num_nulls(config, config_xml) = 1);
為了避免空字符串,您可能需要使用:
check (num_nulls(nullif(trim(config), ''), nullif(trim(config_xml), '')) = 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.