SQL强制执行需要某些逻辑的约束

时间:2017-08-25 01:01:40

标签: sql foreign-keys azure-sql-database composite-key

我不确定如何恰当地提出问题以使Google有所帮助 - 大多数结果都是关于指定外键以便您可以使用JOIN运算符。

修改 为了澄清,我在这里有两个主要概念 - 跟踪器和跟踪器的阅读。跟踪器可以具有任意数量的输入。在特定时间点,跟踪器的读数对于跟踪器上的每个输入都具有值

Tracker
  Id
  Name
  Inputs (List)
    Name

Reading
  Id
  TrackerId
  DateRecorded
  Some other properties
  Inputs (List)
    Value

我使用以下结构对此进行了建模:

Tracker
  Id              (Key)
  Name

TrackerInput
  TrackerId       (Key 0, Foreign key)
  Index           (Key 1)
  Name

Reading
  Id              (Key)
  TrackerId       (Foreign key)
  DateRecorded
  Some other properties

ReadingInput
  ReadingId       (Key 0, Foreign key)
  Index           (Key 1)
  Value

我如何通过SQL强制执行以下约束:

  

读数必须包含它引用的跟踪器上每个输入的值。

1 个答案:

答案 0 :(得分:2)

  

读取上的输入必须指的是跟踪器上的输入,但它需要一个复合外键,该外键当前分为两个表。如果我要强制执行外键约束,则必须加入它们:

SELECT TrackerId, Index -- This is the foreign key I would like to enforce
FROM Readings
JOIN ReadingInputs ON ReadingId = Id

我猜到你的问题的版本,你的意思是你想强制执行Reading& ReadingInput受其加入(因此该视图/查询)的约束,满足约束foreign key (TrackerId, Index) references TrackerInput (TrackerId, Index)

您可以通过将Index添加到Reading,删除当前Reading& ReadingInput FK并添加FK

(TrackerId, Index) references TrackerInput (TrackerId, Index) -- Reading
(ReadingId, Index) references Reading (Id, Index) -- ReadingInput

否则,您可以使用触发器。