ERROR 1215(HY000):无法添加外键约束?

时间:2015-07-23 21:24:16

标签: mysql foreign-keys

有一百万个类似的问题,但我尝试了一切,我找不到解决方案。我有这个表: (使用MySQL)

create table users (
  user_id bigint unsigned not null auto_increment primary key,  
  username varchar(256) not null,
  password varchar(256) not null,
  enabled boolean
);
create unique index ix_users_name on users (username);

create table groups (
    group_id int unsigned not null auto_increment primary key,  
    group_name varchar(50) not null 
);
create unique index ix_groups_name on groups (group_name);

我想创建这个。

create table group_members (
    group_member_id bigint unsigned not null auto_increment primary key,
    user_id bigint not null,
    group_id int not null,
    constraint fk_group_members_1 foreign key(user_id) references users(user_id),
    constraint fk_group_members_2 foreign key(group_id) references groups(group_id)
);
create unique index ix_member_group on group_members (user_id,group_id);

然后抛出

ERROR 1215 (HY000): Cannot add foreign key constraint

你知道发生了什么吗?

1 个答案:

答案 0 :(得分:3)

您在FK两侧的字段定义必须匹配:

t1: user_id bigint unsigned not null auto_increment primary key,  
                   ^^^^^^^^ 
t2: user_id bigint not null,

t1定义为unsigned,这意味着理论上可以在t1中创建一个无法在t2中表示的记录,因为T1的可能ID范围是0-> 2 ^ 64, VS -2 ^ 63->在t2中+ 2 ^ 63。