sql - 如何确保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
这行得通吗?此外,是否有一种将其扩展到更多列的好方法?
解决方案
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)
);
推荐阅读
- python - 有没有办法识别和转换一串普通字符中的非转义四位 Unicode 字符?
- caching - 用于缓存的 Armv8 地址字段?
- hapijs - Apollo Server & 4xx 状态码
- python - 如何使用 python 将数据正确附加到 JSON
- python - @nd 时间给出错误,在 TENSORFLOW 执行期间
- tomcat - Tomcat 8.5 - HTTP2 是否需要证书/SSL
- p5.js - 如何在 p5.js 中将 keyPressed() 转换为移动设备的触摸保持
- python - 保存数据时不会调用模型的 Django clean 方法,而它适用于其他模型
- c++ - 我无法在代码块中编译 c++ 程序。它给了我错误
- git - 意外退出vim编辑器后如何恢复旧的提交消息?