2011-05-03 50 views
2

我有2個表:創造一個 '用戶' 和 '朋友' 關係

_________   ____________ 
| users |   | friends | 
|_______|   |__________| 
| id |   | id_user1 | 
| nick |   | id_user2 | 
|_______|   |__________| 

但是,如果我嘗試加入他們在一起,像

Alter table friends add Foreign Key (id_user1) references users (id) on delete restrict on update restrict; 
Alter table friends add Foreign Key (id_user2) references users (id) on delete restrict on update restrict; 

我得到一個Identical attribute name "id" in entity "friends"錯誤。我將如何做到這一點?

+0

這不是一個'MySQL'錯誤。您是否使用可視化工具來創建關係? – Quassnoi 2011-05-03 12:45:54

+0

當您說join時,意思是通過SELECT/WHERE語句連接兩個表或在這兩個表之間創建外鍵關係。 – mevdiven 2011-05-03 12:51:43

回答

2

這個工作對我來說:

CREATE TABLE users (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB; 
CREATE TABLE friends (id_user1 INT NOT NULL, id_user2 INT NOT NULL) ENGINE=InnoDB; 
Alter table friends add Foreign Key (id_user1) references users (id) on delete restrict on update restrict; 
Alter table friends add Foreign Key (id_user2) references users (id) on delete restrict on update restrict; 
+0

嗯,將引擎從MyISAM更改爲InnoDB可以修復它。謝謝 – dice 2011-05-03 12:48:07

+1

'MyISAM'不支持參照完整性。 – Quassnoi 2011-05-03 12:51:06