mysql - 外键级联更新

时间:2012-08-08 08:10:52

标签: mysql sql foreign-keys foreign-key-relationship

我有一个关于如何使用第二个字段作为约束来更新级联字段的问题。

结构是这样的(我删除了不必要的列):

nodesidNodeidDimension(它们共同构成主键)。

forcesidForce(PK),idNodenodes的外键。idNode)和idDimension

级联更新和删除所有内容。

这种结构似乎出现的问题是:

如果在nodes中我有一个像(1,1)和一个像(1,2)和forces(1,1,1)和(1,1,2)的条目我更新或删除nodes中的第一个条目forces中的两个条目都将受到影响。

我只需要影响那个也有相应idDimension的那个。如何修改当前结构呢?

编辑:表格 - 节点:

CREATE TABLE IF NOT EXISTS `nodes` (
  `idNode` varchar(11) NOT NULL,
  `idDimension` int(10) unsigned NOT NULL,
  `idNetwork` int(10) unsigned NOT NULL DEFAULT '0',
  `level` int(11) unsigned NOT NULL DEFAULT '0',
  `energy` bigint(20) DEFAULT NULL,
  `resources` bigint(20) unsigned NOT NULL DEFAULT '0',
  `x` int(11) NOT NULL,
  `y` int(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `order` tinyint(3) DEFAULT '0' COMMENT 'energy 0\nassemble 1\nupgrade 2',
  `core` tinyint(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`idNode`,`idDimension`),
  KEY `network_dimension` (`idDimension`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Node table';

约束:

 CREATE TABLE IF NOT EXISTS `forces` (
  `idForce` bigint(10) unsigned NOT NULL AUTO_INCREMENT,
  `idNode` varchar(11) NOT NULL,
  `idDimension` int(10) unsigned NOT NULL,
  `drones` bigint(20) DEFAULT NULL,
  `stance` tinyint(3) DEFAULT NULL COMMENT '0 - defense\n1 - neutral\n2 - attack      \n\nIf planet is parano and you are not allied to owner you can only be in attack.\n\nIf owner is allied you can only be in defense or neutral.\n\nIf you are owner you can only be in defense.',
   `order` tinyint(3) DEFAULT '0' COMMENT 'extract energy 1\nbuild node 2\nreplicate 3\nmove 4',
  `value` text,
   PRIMARY KEY (`idForce`),
   KEY `idNode` (`idNode`,`idDimension`),
   KEY `idDimension` (`idDimension`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

-

- 表forces

的约束
  ALTER TABLE `forces`
    ADD CONSTRAINT `forces_ibfk_2` FOREIGN KEY (`idDimension`) REFERENCES `nodes`  (`idDimension`) ON DELETE CASCADE ON UPDATE CASCADE,
    ADD CONSTRAINT `fk_forces_nodes1` FOREIGN KEY (`idNode`, `idDimension`) REFERENCES `nodes` (`idNode`, `idDimension`) ON DELETE NO ACTION ON UPDATE NO ACTION,
    ADD CONSTRAINT `forces_ibfk_1` FOREIGN KEY (`idNode`) REFERENCES `nodes` (`idNode`) ON DELETE CASCADE ON UPDATE CASCADE;

我的约束不能正常工作,所以我可以随意忽略它们。)。

1 个答案:

答案 0 :(得分:7)

有两个奇怪的外键(forces_ibfk_1forces_ibfk_2)引用非唯一字段。删除它们 -

ALTER TABLE forces DROP FOREIGN KEY forces_ibfk_1;
ALTER TABLE forces DROP FOREIGN KEY forces_ibfk_2;

然后使用CASCADE操作选项 -

重新创建引用唯一字段对的fk_forces_nodes1
ALTER TABLE forces
  DROP FOREIGN KEY fk_forces_nodes1;

ALTER TABLE orces
  ADD CONSTRAINT fk_forces_nodes1 FOREIGN KEY (idNode, idDimension)
    REFERENCES nodes(idNode, idDimension) ON DELETE CASCADE ON UPDATE CASCADE;