创建“用户”和“朋友”关系

时间:2011-05-03 12:38:16

标签: mysql sql

我有两张桌子:

_________          ____________
| 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" 错误。我该怎么做?

1 个答案:

答案 0 :(得分: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;