【问题标题】:Attribute that is not null when an other attribute is also not null in SQL当 SQL 中的其他属性也不为空时,该属性不为空
【发布时间】:2020-05-13 15:52:02
【问题描述】:

我想为文章创建一个表,它可以有(但不需要有)指向 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'
);

【问题讨论】:

  • 有什么问题?您使用的是哪个 dbms?
  • check (imgType IN ( 'png', 'svg', 'jpg'))
  • 我正在使用 postgresql,问题是如何使 imgType 属性不为空,但前提是 imgSrc 也不为空。所以我不需要一个 imgSrc 值,但如果我有一个,我还需要一个 imgType 的值。
  • @DerWolferl check imgSrc is null or imgType is not null。这样,如果 imgSrc 为 null,则约束通过,如果 imgSrc 不是,则检查 imgType 是否为 null。

标签: sql postgresql constraints create-table notnull


【解决方案1】:

添加一个新的约束来检查两个值是否为空或两个值都不为空

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

【讨论】:

  • 如果 imgSrc 为空,这将强制 imgType 为空,根据原文,这不是必需的。如果这个额外的约束不相关或不受欢迎,那么你可以检查imgSrc is null or imgType is not null。这样,如果 imgSrc 为空,您甚至不会检查 imgType 的值。
猜你喜欢
  • 1970-01-01
  • 2020-09-28
  • 2012-11-12
  • 2019-02-06
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
相关资源
最近更新 更多