首页 > 解决方案 > 当 SQL 中的其他属性也不为空时,该属性不为空

问题描述

我想为文章创建一个表,它可以有(但不需要有)指向 img-Source 的链接。对于所有具有链接的文章,还需要一个 img-Type(应该是“png”、“svg”或“jpg”)。我不太明白如何使 img-Type 字段不为空,仅适用于 img-Src 字段不为空的值。

这是我的代码(字段 img-Type 和 img-Src 没有非空/空约束)

create TABLE Article(
articleID varchar(15) primary key ,
articleDescription varchar (80) null ,
imgSrc varchar (20)  ,
imgType  char(3),
check imgType = 'png' or imgType = 'svg' or imgType = 'jpg'
);

标签: sqlpostgresqlconstraintscreate-tablenotnull

解决方案


添加一个新约束,您可以在其中检查两个值是否为空或两个值都不为空

check (imgSrc is not null and imgType is not null 
    or imgSrc is null and imgType is null)

推荐阅读