当删除某些行和关系时,我在清理数据库时遇到问题。
CREATE TABLE IF NOT EXISTS `cms_users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`id_account_type` smallint(2) unsigned NOT NULL,
PRIMARY KEY (`id`)
);
以上是部分用户。这些用户有孩子,他们存储在其他表中:
CREATE TABLE IF NOT EXISTS `cms_users_relations` (
`id_user` int(10) unsigned NOT NULL,
`id_parent` int(10) unsigned DEFAULT NULL,
UNIQUE KEY `id_user` (`id_user`),
KEY `constraint_9` (`id_parent`)
);
ALTER TABLE `cms_users_relations`
ADD CONSTRAINT `constraint_8` FOREIGN KEY (`id_user`) REFERENCES `cms_users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `constraint_9` FOREIGN KEY (`id_parent`) REFERENCES `cms_users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
问题是当我从 cms_users 中删除父级时,所有子级也应该被删除,但他们没有。我为此目的创建了一个触发器,但它不起作用:
DELIMITER //
CREATE TRIGGER `delete_user` AFTER DELETE ON `cms_users_relations`
FOR EACH ROW BEGIN
DELETE FROM cms_users WHERE OLD.id_user = cms_users.id;
END
//
DELIMITER ;
看起来mysql服务器不用担心我们正在删除用户,然后通过外键删除关系,然后我们应该放置触发器......
有任何想法吗?