2010-02-23 88 views
2

我在mysql中有以下代碼。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_idusertype_id如表relation如表employee外鍵user_idusertype_id的統一。

你知道該怎麼做嗎?

非常感謝。

回答

1

您可以user_idusertype_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等於對方。老實說,這聽起來像是浪費空間。

+0

您還應該級聯更新 – arthurprs 2010-02-23 17:51:56

+0

@thanks vanessa,實際上,我想爲user_id和usertype_id添加一個外鍵作爲一個整體。那可能嗎? – 2010-02-23 19:31:32

0

您可以引入一個觸發器來保證e_id和user_id包含相同的值,但我同意上一張海報。重點是什麼?

+0

@Greg,謝謝。我想用user_id作其他用途,它不應該是主鍵。所以我必須這樣做。你有什麼想法? – 2010-02-23 19:33:07