MySQL DB中的外键约束导致错误

时间:2016-01-08 09:13:21

标签: mysql sql database innodb

我正在尝试实现一个外键约束但是mysql一直给我一个错误有两个表“groups”表和“members”表。我在这些表之间有多对多的关系因此使用了第三个表“members_groups”表用于多对多关系。注意:“groups”和“members”表已创建并包含数据,但我现在想要添加“members_groups”表。以下是sql代码:

以下是members表的脚本。

CREATE TABLE IF NOT EXISTS `members` (
  `member_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` char(128) NOT NULL,
  `salt` char(128) NOT NULL,
  `group_id` bigint(64) unsigned NOT NULL,
  `perm_override_add` bigint(64) unsigned NOT NULL,
  `perm_override_remove` bigint(64) unsigned NOT NULL,
  PRIMARY KEY (`member_id`),
  KEY `member_id` (`member_id`)
) ENGINE=InnoDB;

组表的脚本

CREATE TABLE IF NOT EXISTS `groups` (
  `group_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `group_name` varchar(50) NOT NULL,
  `permission` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`group_id`)
) ENGINE=InnoDB 

member_groups表的

脚本

CREATE TABLE members_groups
(
    member_id INT(11) NOT NULL ,  
    group_id INT(10) NOT NULL ,  
    PRIMARY KEY (member_id, group_id),  
    FOREIGN KEY (member_id) REFERENCES members(member_id) ON UPDATE CASCADE,  
    FOREIGN KEY (group_id) REFERENCES groups(group_id) ON UPDATE CASCADE
)  ENGINE = InnoDB

这是我从mysql管理控制台获得的错误。

enter image description here

感谢。

1 个答案:

答案 0 :(得分:1)

您需要在表格中输入相同的类型。在您已定义的groups表中

`group_id` int(10) unsigned NOT NULL AUTO_INCREMENT, 

而在你的members_groups表中,它是

group_id INT(10) NOT NULL ,

尝试进行更改

CREATE TABLE members_groups
(
    member_id INT(11) NOT NULL ,  
    group_id INT(10) unsigned NOT NULL ,  --The datatype should be same as group_id in `groups` table
    PRIMARY KEY (member_id, group_id),  
    FOREIGN KEY (member_id) REFERENCES members(member_id) ON UPDATE CASCADE,  
    FOREIGN KEY (group_id) REFERENCES `groups`(group_id) ON UPDATE CASCADE
)  ENGINE = InnoDB;

<强> SQL FIDDLE DEMO