我创建了以下表格,并且不知道为什么我的外键约束脚本无效。
CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`project_id` varchar(60) NOT NULL,
`project_name` varchar(500) NOT NULL,
`cons_bal` int(11) NOT NULL,
`non_cons_bal` int(11) NOT NULL,
`budget_head` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
这是我的另一张桌子:
CREATE TABLE IF NOT EXISTS `project_map` (
`id` int(11) NOT NULL,
`project_id` varchar(60) NOT NULL,
`head` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
这是我的添加约束行:
alter table project_map add constraint p_map_fk001 foreign key (`project_id`) references project(`project_id`)
任何帮助都会很好。谢谢。
答案 0 :(得分:1)
在引用的表中,必须有一个索引,其中引用的列被列为相同顺序的第一列。
参考:http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
所以试试:
CREATE TABLE `project` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`project_id` varchar(60) NOT NULL,
`project_name` varchar(500) NOT NULL,
`cons_bal` int(11) NOT NULL,
`non_cons_bal` int(11) NOT NULL,
`budget_head` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `project_id` (`project_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `project_map` (
`id` int(11) NOT NULL,
`project_id` varchar(60) NOT NULL,
`head` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `project_id` (`project_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
ALTER TABLE `project_map` ADD CONSTRAINT
`p_map_fk001` FOREIGN KEY (`project_id`)
REFERENCES project(`project_id`);