首页 > 解决方案 > 如何确保postgresql表中只有一列不为空

问题描述

我正在尝试设置一个表并为其添加一些约束。我计划使用部分索引来添加约束以创建一些复合键,但遇到了处理 NULL 值的问题。我们有一种情况,我们希望确保在一个表中,只为给定行填充两列中的一列,并且填充的值是唯一的。我试图弄清楚如何做到这一点,但我遇到了困难。也许是这样的:

CREATE INDEX foo_idx_a ON foo (colA) WHERE colB is NULL
CREATE INDEX foo_idx_b ON foo (colB) WHERE colA is NULL

这行得通吗?此外,是否有一种将其扩展到更多列的好方法?

标签: sqlpostgresqlindexingconstraints

解决方案


Another way to write this constraint is to use the num_nonulls() function:

create table table_name 
(
  a integer, 
  b integer, 
  check ( num_nonnulls(a,b) = 1)
);

This is especially useful if you have more columns:

create table table_name 
(
  a integer, 
  b integer, 
  c integer,
  d integer,
  check ( num_nonnulls(a,b,c,d) = 1)
);

推荐阅读