MySQL对单个表的多个外键约束

时间:2015-05-19 13:34:55

标签: mysql foreign-keys constraints

我有2个不相关的表,但每个表都有相同的列类型我称为'somefield'

CREATE TABLE `table1` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `somefield` varchar(255) NOT NULL DEFAULT '',
 PRIMARY KEY (`id`),
 UNIQUE KEY `somefield` (`somefield`),
)

CREATE TABLE `table2` (
 `id` int(5) NOT NULL AUTO_INCREMENT,
 `somefield` int(20) DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `somefield` (`somefield`)
)

插入这些表中的任何一个后,我在此表中插入'somefield'值。

CREATE TABLE `table3` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `somefield` varchar(255) NOT NULL DEFAULT '',
 PRIMARY KEY (`id`),
 UNIQUE KEY `somefield` (`somefield`),
 CONSTRAINT `FK_table3` FOREIGN KEY (`somefield`) REFERENCES `table1` (`somefield`) ON DELETE CASCADE ON UPDATE CASCADE
)

目前,如果我删除table1中的一行,则在table3中删除相同的行。我可以插入到table1并在table3上执行插入而没有任何问题但是如果我插入到table2并尝试插入到table3中我会收到此错误

  

完整性约束违规:1452无法添加或更新子行:   外键约束失败

我知道这与外键约束有关,因为它期望table1中存在'somefield'值。我想知道的是如何添加另一个约束。

ALTER TABLE table3 ADD CONSTRAINT FK_table3 FOREIGN KEY (`somefield`) REFERENCES `table2` (`somefield`)  ON DELETE CASCADE ON UPDATE CASCADE;

我是否需要创建2个表来充当table1 / table3和table2 / table3之间的转换?

1 个答案:

答案 0 :(得分:0)

我能够通过创建一个表来对其进行排序,其他3个表都链接到这个表。

如果在新表中删除了一行,则会在其他表中删除生成的行。

CREATE TABLE IF NOT EXISTS `table1` (
  `id` tinyint(3) NOT NULL AUTO_INCREMENT,
  `somefield` varchar(12) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `somefield` (`somefield`)
);

CREATE TABLE IF NOT EXISTS `table2` (
  `id` tinyint(3) NOT NULL AUTO_INCREMENT,
  `somefield` varchar(12) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `somefield` (`somefield`)
);

CREATE TABLE IF NOT EXISTS `table3` (
  `id` tinyint(3) NOT NULL AUTO_INCREMENT,
  `somefield` varchar(12) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `somefield` (`somefield`)
);

CREATE TABLE IF NOT EXISTS `supertable` (
  `somefield` varchar(12) NOT NULL DEFAULT '',
  PRIMARY KEY (`somefield`),
  UNIQUE KEY `somefield` (`somefield`)
);

ALTER TABLE `table1`
  ADD CONSTRAINT `FK_table1` FOREIGN KEY (`somefield`) REFERENCES `supertable` (`somefield`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `table2`
  ADD CONSTRAINT `FK_table2` FOREIGN KEY (`somefield`) REFERENCES `supertable` (`somefield`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `table3`
  ADD CONSTRAINT `FK_table3` FOREIGN KEY (`somefield`) REFERENCES `supertable` (`somefield`) ON DELETE CASCADE ON UPDATE CASCADE;