【问题标题】:Two columns can not be null at the same time in sqlsql中两列不能同时为null
【发布时间】:2018-07-27 02:16:38
【问题描述】:

假设有一个表叫

员工

ID number, name varchar(24 char), address varchar2(100 char), alternateAddress(100 char), sex varchar2(10 char)

现在我想设置约束,使得地址和备用地址都不能为空,即 可能的情况是:

  • address 为 null,alternateAddress 不为 null
  • alternateAddress 为空且地址不为空
  • alternateAddress 不为空且地址不为空

但不会发生 Employee 表中的任何记录都插入了alternateAddress 和地址都为空

【问题讨论】:

  • 请在提出此类问题时指定 RDBMS,例如MySQL、SQL-Server、Oracle、Postgres 等

标签: sql


【解决方案1】:

像这样为你的表创建一个约束:

ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [CK_OneAddress] CHECK  ((NOT [address] IS NULL) OR (NOT [alternateAddress] IS NULL))
GO

ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [CK_OneAddress]
GO

【讨论】:

  • 我在下面使用了类似于你建议的 sql 脚本,它工作得非常好 ALTER TABLE Employee ADD CONSTRAINT CK_OneAddress CHECK (NOT ((alternateAddress IS NULL) AND (address IS NULL)));跨度>
  • 没问题,关于布尔代数,你的脚本相当于我的建议。请您将我的答案标记为已接受?谢谢!
【解决方案2】:

像这样创建你的约束:

(address is null and alternateAddress is not null) or 
(alternateAddress is null and address is not null) or 
(alternateAddress is not null and address is not null)

【讨论】:

    【解决方案3】:

    你不能用吗:

    IF(COALESCE(address, alternateAddress) IS NOT NULL)
    

    WHERE (COALESCE(address, alternateAddress) IS NOT NULL)
    

    还是那种不好的形式?

    【讨论】:

      【解决方案4】:

      根据德摩根定律,not (A and B) 等价于 (not A or not B),因此

      (address is not null OR alternateAddress is not null)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-14
        • 2012-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多