【问题标题】:Foreign Key Constraints with multiple keys具有多个键的外键约束
【发布时间】:2016-02-11 15:26:51
【问题描述】:

我敲了一个简单的桌子设计:

如您所见,tAttachments 具有 ImagesPlayerNamesPlayerNumbers 的外键。下面仔细看看这张表:

我需要在表上创建一个约束,声明 tAttachments 必须至少有 1 个外键集。 有谁知道我该怎么做?

【问题讨论】:

  • 你用的是哪个dbms?
  • 我的不一样,我的要求只能设置1。所以 1, 0, 0 很好; 0, 1, 0 很好,0, 0, 1 很好,但是 1,1, 0 不是,1, 1, 1 或 0, 0, 0 也不是。我希望这是有道理的。 @PieroAlberto 它是 MSSQL,所以我使用的是 SQL Management Studio。

标签: sql-server entity-framework


【解决方案1】:

我不知道如何在数据库设计步骤中执行此操作,但您可以执行 trigger INSERT 和触发器 UPDATE。通过这种方式,您可以检查是否遵守此约束。

类似:

create trigger tAttachmentsCheck on tAttachments for insert, update as
begin
if exists (select *
    from inserted i
    where (i.ImageId <> NULL and PlayerNameId <> NULL)
    or (i.ImageId <> NULL and PlayerNameId <> NULL and PlayerNumberId <> NULL)
    or (i.ImageId <> NULL and PlayerNumberId <> NULL)
    or (i.PlayerNumberId <> NULL and PlayerNameId <> NULL))

    rollback transaction
end

【讨论】:

    【解决方案2】:

    一个简单的检查约束:

    ImageID is NULL and PlayerNameID is NULL and PlayerNumberID is NOT NULL
    or ImageID is NULL and PlayerNameID is NOT NULL and PlayerNumberID is NULL
    or ImageID is NOT NULL and PlayerNameID is NULL and PlayerNumberID is NULL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      相关资源
      最近更新 更多