我的MySQL上有五个表,都是InnoDB。
常规表
Table list
Table proc
Table views
联结表
Table l_p
Table l_p_views
CREATE TABLE IF NOT EXISTS `list` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `proc` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `view` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `l_proc` (
`listId` int(10) unsigned NOT NULL,
`procId` int(10) unsigned NOT NULL,
PRIMARY KEY (`listId`,`procId`),
KEY `l_process_ibfk_2` (`procId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `l_proc`
ADD CONSTRAINT `l_proc_ibfk_1` FOREIGN KEY (`listId`) REFERENCES `list` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `l_proc_ibfk_2` FOREIGN KEY (`procId`) REFERENCES `proc` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE IF NOT EXISTS `l_p_view` (
`listd` int(10) unsigned NOT NULL,
`procId` int(10) unsigned NOT NULL,
`viewId` int(10) unsigned NOT NULL,
KEY `listId` (`listId`,`procId`,`viewId`),
KEY `view` (`viewId`),
KEY `l_p_view_ibfk_2_idx` (`procId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `l_p_view`
ADD CONSTRAINT `l_p_view_ibfk_1` FOREIGN KEY (`listId`) REFERENCES `l_proc` (`listId`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `l_p_view_ibfk_3` FOREIGN KEY (`viewId`) REFERENCES `view` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `l_p_view_ibfk_4` FOREIGN KEY (`procId`) REFERENCES `l_proc` (`procId`) ON DELETE CASCADE ON UPDATE CASCADE;
这个想法是,如果删除了列表记录,那么所有引用的l_proc和l_p_view记录也会被删除。这确实有效。
但是,当我使用listId和procId作为查询删除l_proc中的记录时,l_p_view中具有相同listId的所有记录都会立即被删除 - 它们的procId与提交的记录不同并不重要。 l_proc的原始删除查询。
我可以在这里找到什么?
RGDS, P上。
答案 0 :(得分:1)
我会尝试替换它:
ALTER TABLE `l_p_view`
ADD CONSTRAINT `l_p_view_ibfk_1` FOREIGN KEY (`listId`) REFERENCES `l_proc` (`listId`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `l_p_view_ibfk_3` FOREIGN KEY (`viewId`) REFERENCES `view` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `l_p_view_ibfk_4` FOREIGN KEY (`procId`) REFERENCES `l_proc` (`procId`) ON DELETE CASCADE ON UPDATE CASCADE;
用这个:
ALTER TABLE `l_p_view`
ADD CONSTRAINT `l_p_view_ibfk_1` FOREIGN KEY (`listId`,`procId`) REFERENCES `l_proc` (`listId`,`procId`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `l_p_view_ibfk_3` FOREIGN KEY (`viewId`) REFERENCES `view` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
区别在于后者中有一个复合外键,意味着只有l_p_view
中与list_id
和 proc_id
匹配的l_proc
行。 <{1}}表中已删除的行将被删除。