[英]Adding table reference constraints after table creation MySQL
我有两个表,分别代表兴趣和产品。 我正在实现它们之间的many_many关系。 创建表时,我忽略创建表约束以确保在删除产品或利息记录时都删除分配表的记录。
兴趣表
CREATE TABLE IF NOT EXISTS `interests` (
`id` int(11) NOT NULL auto_increment,
`interest` varchar(255) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=62 ;
产品表
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL auto_increment,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=65 ;
作业表
CREATE TABLE IF NOT EXISTS `interest_product_assignment` (
`id` int(11) NOT NULL auto_increment,
`interest_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `product` (`product_id`),
KEY `interest` (`interest_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
我尝试添加此约束的尝试似乎失败了-
ALTER TABLE `interest_product_assignment` ADD CONSTRAINT `product` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE `interest_product_assignment` ADD CONSTRAINT `interest` FOREIGN KEY (`interest_id`) REFERENCES `interest` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
删除产品记录时,不会删除相应的分配记录。
关于此的一些问题:
添加外键不会在MyISAM表上给出警告/错误,但不支持。
在创建外键之前,您需要将MyISAM更改为InnoDB,它将可以正常工作。
从MySQL官方手册中:
在稍后的阶段,还将为MyISAM表实现外键约束。
http://dev.mysql.com/doc/refman/5.7/zh-CN/ansi-diff-foreign-keys.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.