当其他属性在SQL中也不为null时,该属性不为null
我想为文章创建一个表,它可以(但不需要)有一个指向img源的链接。对于包含链接的所有文章,还需要img类型(应该是“png”、“svg”或“jpg”)。我不太明白如何使img类型字段不为null,而仅针对img Src字段不为null的值 这是我的代码(img Type和img Src字段没有NOTNULL/null约束)当其他属性在SQL中也不为null时,该属性不为null,sql,postgresql,constraints,create-table,notnull,Sql,Postgresql,Constraints,Create Table,Notnull,我想为文章创建一个表,它可以(但不需要)有一个指向img源的链接。对于包含链接的所有文章,还需要img类型(应该是“png”、“svg”或“jpg”)。我不太明白如何使img类型字段不为null,而仅针对img Src字段不为null的值 这是我的代码(img Type和img Src字段没有NOTNULL/null约束) 添加一个新约束,在该约束中检查两个值是否都为null或两个值是否都不为null check (imgSrc is not null and imgType is not nu
添加一个新约束,在该约束中检查两个值是否都为null或两个值是否都不为null
check (imgSrc is not null and imgType is not null
or imgSrc is null and imgType is null)
问题是什么?您正在使用哪个dbms?
检查(imgType IN('png','svg','jpg'))
我正在使用postgresql,问题是如何使imgType属性不为null,但前提是imgSrc也不为null。因此,我不需要imgSrc值,但如果我有imgSrc值,我还需要imgType的值。@DerWolferl检查imgSrc是否为null或imgType是否为null
。这样,如果imgSrc为null,则约束将传递,如果imgSrc为null,则检查imgType是否为null。如果imgSrc为null,则强制imgType为null,这根据原始约束是不必要的。如果此附加约束不相关或不受欢迎,则只需检查imgSrc是否为null或imgType是否为null
。这样,如果imgSrc
为空,您甚至不检查imgType
的值。
check (imgSrc is not null and imgType is not null
or imgSrc is null and imgType is null)