1

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

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

nodes带有列的表和idNodeidDimension它们一起构成主键)。

forces包含列idForce(PK)、 ( .idNode的外键)和. 的表nodesidNodeidDimension

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

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

如果在nodes我有一个像 (1, 1) 和一个像 (1, 2) 和在(1, 1, 1) 和 (1, 1, 2) 中的条目,并且我从两个条目中forces更新或删除第一个条目将是做作的。nodesforces

我只需要影响也具有相应 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;

我的约束不起作用,所以请随意忽略它们:)。

4

1 回答 1

8

有两个奇怪的外键 ( forces_ibfk_1and forces_ibfk_2) 指的是非唯一字段。删除它们 -

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

然后fk_forces_nodes1使用 CASCADE 操作选项重新创建引用唯一字段对 -

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;
于 2012-08-08T10:13:51.290 回答