数据库
首页 > 数据库> > MySQL多层次约束

MySQL多层次约束

作者:互联网

我在用MySQL强制执行数据模型时遇到了麻烦,我想知道是否有更好的方法可以做到这一点.

模型:

Platforms <- Has many groups

Groups <- Has one platform, Has many SymbolSets

SymbolSets <- Belongs to many groups

我的问题是SymbolSet只能属于具有相同平台的组.因此,如果平台A具有带有SymbolSet A的组A,则带有Group B的Platform B应该无法获取SymbolSet A,但是Platform A中的任何组都应该能够获取它.

现在,我在SymbolSets和Groups之间有一个链接表,并且在代码中每个平台都实施了唯一性,但是我宁愿在DB中实施一个解决方案,以便没人能弄乱它并破坏事情.我不希望一开始就没有这种多对多的关系,但这确实不适合我们的业务模型.

解决方法:

Platform     
----------
PlatformId
PRIMARY KEY (PlatformId)

Grouping        
----------
GroupingId
PlatformId
PRIMARY KEY (GroupingId, PlatformId)
FOREIGN KEY (PlatformId)            
  REFERENCES Platfrom(PlatformId)

SymbolSet         
----------
SymbolSetId 
PRIMARY KEY (SymbolSetId)

将SymbolSet分配给组(SymbolSetToGroup中的新行)时,首先必须将其分配给该组所属的同一Platform(因此,首先在SymbolSetAssigned中创建新行).

SymbolSetAssigned               --- assigned to Platform
-----------------
SymbolSetId 
PlatformId
PRIMARY KEY (SymbolSetId)
UNIQUE KEY (SymbolSetId, PlatformId)
FOREIGN KEY (SymbolSetId)                              
  REFERENCES SymbolSet(SymbolSetId)
FOREIGN KEY (PlatformId)            
  REFERENCES Platfrom(PlatformId)

SymbolSetToGroup
----------------
SymbolSetId 
GroupingId
PlatformId
PRIMARY KEY (SymbolSetId, GroupingId)
FOREIGN KEY (SymbolSetId, PlatformId)                              
  REFERENCES SymbolSetAssigned(SymbolSetId, PlatformId)
FOREIGN KEY (GroupingId, PlatformId)             
  REFERENCES Grouping(GroupingId, PlatformId)

标签:database-design,mysql
来源: https://codeday.me/bug/20191202/2085228.html