我有一个交叉引用表,其中包含两个外键。 RoleId(PK,FK)和PermissionId(PK,FK)。 Role表和Permission表都包含名为ApplicationId的外键列。我想确保无法将记录插入到交叉引用表中,该交叉引用表包含与ApplicationId 1关联的RoleId和与ApplicationId关联的PermissionId 2.除了使用触发器实现此类完整性之外,还有其他方法吗?
答案 0 :(得分:1)
您可以将applicationId列添加到交叉引用表中,然后扩展Role和Permission表的外键以包含applicationId列。这提供了所需的参照完整性。
这是mysql中已解决的架构
CREATE TABLE `application` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `permission` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`applicationId` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `id_app` (`id`,`applicationID`),
CONSTRAINT `FK_perm_app` FOREIGN KEY (`applicationID`) REFERENCES `application` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `role` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`applicationId` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `id_app` (`id`,`applicationID`),
CONSTRAINT `FK_role_app` FOREIGN KEY (`applicationID`) REFERENCES `application` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `role_permission_application` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`roleID` int(11) unsigned NOT NULL,
`permissionID` int(11) unsigned NOT NULL,
`applicationID` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_role` (`roleID`,`applicationID`),
KEY `FK_permission` (`permissionID`,`applicationID`),
CONSTRAINT `FK_permission` FOREIGN KEY (`permissionID`,`applicationID`) REFERENCES `permission` (`id`,`applicationID`),
CONSTRAINT `FK_role` FOREIGN KEY (`roleID`,`applicationID`) REFERENCES `role` (`id`,`applicationID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;