MySQL:如何添加外键

时间:2010-02-23 16:18:01

标签: mysql foreign-keys

我在mysql中有以下代码。

create table employee(
    e_id int(10) not null auto_increment,
    user_id int(10),
    usertype_id default 1,
    name varchar(50),
    primary key (e_id)
);
create table relation(
    r_id int(10) not null auto_increment,
    user_id int(10) not null,
    usertype_id int(10) not null,
    interest_id int(10) not null,
    primary key (id)
);

首先,我希望user_id与列e_id具有相同的值;

然后,我想在表user_id中将usertype_idrelation作为一个统一添加为表user_idusertype_id的外键{1}}。

你知道怎么做吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以在表user_id中将usertype_idrelation作为表employee中相同列的外键,如下所示:

create table relation(
    r_id int(10) not null auto_increment,
    foreign key user_id references employee(user_id),
    foreign key usertype_id references employee(usertype_id),
    interest_id int(10) not null,
    primary key (id)
);

e_iduser_id相互平等,我无法帮助您。老实说,这听起来像是浪费空间。

答案 1 :(得分:0)

您可以引入一个触发器来保证e_id和user_id包含相同的值,但我同意上一张海报。有什么意义?