是的,有办法。将 的主键列包含Block
到关联表中,并使用它来扩展外键约束:
CREATE TABLE Blocks
( BlockID INT
, PRIMARY KEY (BlockID)
) ;
CREATE TABLE Foos
( BlockID INT
, FooID INT
, PRIMARY KEY (FooID)
, FOREIGN KEY (BlockID)
REFERENCES Blocks (BlockID)
, UNIQUE (BlockID, FooID) -- the Unique constraints are needed for
) ;
CREATE TABLE Bars
( BlockID INT
, BarID INT
, PRIMARY KEY (BarID)
, FOREIGN KEY (BlockID)
REFERENCES Blocks (BlockID)
, UNIQUE (BlockID, BarID) -- the composite FKs below
) ;
CREATE TABLE Foo_Bars -- the m:n association tabletable
( BlockID INT
, FooID INT
, BarID INT
, PRIMARY KEY (FooID, BarID)
, FOREIGN KEY (BlockID, FooID) -- composite FK constraints to Foos
REFERENCES Foos (BlockID, FooID)
, FOREIGN KEY (BlockID, BarID) -- and Bars
REFERENCES Bars (BlockID, BarID)
) ;