SQL:检查约束取决于其他表

时间:2012-03-21 17:22:31

标签: sql check-constraints

我有3个表:会员,雇主和位置。

会员包含MemberID,EmployerID和LocationID。
雇主有EmployerID 位置有EmployerID,LocationID。

Member <<---> Employer
Location <<---> Employer
Member <---> Location

我需要对名为

的成员进行检查约束
  

会员的位置为空或属于其雇主的位置

如何将Member.LocationID约束到具有相同EmployerID的位置?即:Member.EmployerID = Location.EmployerID

1 个答案:

答案 0 :(得分:1)

您可以在Location (EmployerID, LocationID)上创建一个唯一的索引/主键(我认为这可能就是这种情况)

然后有一个多列FK引用Member

CREATE TABLE Location
(
EmployerID INT,
LocationID INT,
PRIMARY KEY (EmployerID,LocationID)
)


CREATE TABLE Member
(
MemberID INT PRIMARY KEY,
EmployerID INT,
LocationID INT,
FOREIGN KEY (EmployerID,LocationID)
    REFERENCES Location (EmployerID,LocationID)
)