让我们想象我有两张桌子:
Regions
(RegionID,RegionName,RegionRank)其中RegionRank
可以是Primary
或Secondary
Country
(CountryID,CountryName,Primary_RegionID,Secondary_RegionID)
区域表可能如下所示:
RegionID RegionName RegionRank
1 Nordic Primary
2 NordEuropean Secondary
3 GermanSpeaking Primary
4 Iberia Primary
5 SouthEuropean Secondary
国家/地区表格可能如下所示:
CountryID CountryName Primary_RegionID Secondary_RegionID
1 Sweden 1 (Nordic) 2 (NordEuropean)
2 Germany 3 (GermanSpeaking) 2 (NordEuropean)
3 Spain 4 (Iberia) 5 (SouthEuropean)
我想为Country
创建2个外键。
Country.Primary_RegionID = fk_Primary_RegionID
引用Region(RegionID, RegionRank = "Primary")
Country.Secondary_RegionID = fk_Primary_RegionID
引用Region(RegionID, RegionRank = "Secondary")
我该怎么做?如何使用此类检查约束创建fk?我可以创建2个不同的表(Region_Primary)和(Region_Secondary),但我找不到一个优雅的解决方案。也许这更容易。
由于
答案 0 :(得分:2)
这有点棘手,但您可以使用计算列和其他唯一键来完成。
alter table regions
add constraint unique unq_regions_primary on (RegionRank, RegionName);
alter table countries add PrimaryRank as ('Primary');
alter table countries add SecondaryRank as ('Secondary');
alter table countries
add constraint fk_countries_primary foreign key (PrimaryRank, Primary_RegionID) references regions (RegionRank, RegionId);
alter table countries
add constraint fk_countries_secondary foreign key (SecondaryRank, Secondary_RegionID) references regions (RegionRank, RegionId);