我有两个表 - tree_hierarchy:
tree_hierarchy | CREATE TABLE `tree_hierarchy` (
`tree_id` int(10) unsigned NOT NULL,
`time_segment` date NOT NULL,
`parent_node_id` int(10) unsigned NOT NULL,
`child_node_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`tree_id`,`time_segment`,`parent_node_id`,`child_node_id`),
KEY `fk_tree_hierarchy_child_node_idx` (`child_node_id`,`time_segment`),
KEY `fk_tree_hierarchy_parent_node_idx` (`parent_node_id`,`time_segment`),
KEY `fk_tree_hierarchy_tree_id_idx` (`tree_id`),
KEY `fk_tree_hierarchy_child_def` (`time_segment`),
CONSTRAINT `fk_tree_hierarchy_tree_id` FOREIGN KEY (`tree_id`) REFERENCES `tree` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8
和node_instance:
node_instance | CREATE TABLE `node_instance` (
`id` int(10) unsigned NOT NULL,
`node_id` int(10) unsigned NOT NULL,
`time_segment` date NOT NULL,
`name` varchar(128) NOT NULL,
`sharing` enum('Private','Inherited','User','Open') NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_node_ts` (`time_segment`,`node_id`),
KEY `fk_node_instance_node_1` (`node_id`),
KEY `fk_node_instance_time_segment_idx` (`time_segment`),
CONSTRAINT `fk_node_instance_node_id` FOREIGN KEY (`node_id`) REFERENCES `node` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_node_instance_time_segment` FOREIGN KEY (`time_segment`) REFERENCES `time_segment` (`segment`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8
尝试设置约束时:
ALTER TABLE `tree_hierarchy` ADD CONSTRAINT `fk_tree_hierarchy_child_xyz`
FOREIGN KEY (`child_node_id` , `time_segment` )
REFERENCES `node_instance` (`node_id` , `time_segment` )
ON DELETE NO ACTION
ON UPDATE NO ACTION;
我明白了:
ERROR 1005 (HY000): Can't create table 'empty_structure.#sql-4e8_28b1' (errno: 150)
这意味着我的结构不合适。但我认为两个字段(两个表中的node_id和time_segment都相同)。当我创建简单的约束时,一切都很好:
ALTER TABLE `tree_hierarchy` ADD CONSTRAINT `fk_tree_hierarchy_child_abcd`
FOREIGN KEY (`time_segment` )
REFERENCES `node_instance` (`time_segment` )
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0
和
ALTER TABLE `tree_hierarchy` ADD CONSTRAINT `fk_tree_hierarchy_child_efgh`
FOREIGN KEY (`child_node_id` )
REFERENCES `node_instance` (`node_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Query OK, 0 rows affected (0.19 sec)
Records: 0 Duplicates: 0 Warnings: 0
我确保外键名称不同(请注意xyz,abcd,efgh后缀)。
前者ADD CONSTRAINT
出了什么问题?
答案 0 :(得分:0)
一段时间后,我发现在node_instance中我错过了相应的复杂密钥(node_id
,time_segment
)。相反,我有(time_segment
,node_id
) - 这就是mysql失败的原因。添加缺失密钥后,一切正常。