我有一个数据库,其中的每个条目都代表一个用户。现在我希望每个用户都能有朋友,IE,每个条目都会有一个字段"朋友",它会有多个代表其他用户的项目。
我不确定这是否可能,如果不可能,我很想知道我如何才能做到这一点。
如果重要的话,我的数据库是MySQL。
谢谢。
使用另一个名为friends
的表
例如
users table
-----------
id name
1 tom
2 peter
3 jane
现在,如果你想让用户1与2和3成为朋友,你的表看起来像这个
friends table
-------------
user_id friend_id
1 2
1 3
为了扩展@juergend的答案,我会采用以下方法(我使用了他已经建议的用户名):
create table users (
id int not null auto_increment primary key,
name varchar(20)
);
create table friends (
user1 int not null references users(id),
user2 int not null references users(id)
);
insert into users (name) values ('tom'), ('peter'), ('jane');
select * from users;
+----+-------+
| id | name |
+----+-------+
| 1 | tom |
| 2 | peter |
| 3 | jane |
+----+-------+
3 rows in set (0.00 sec)
-- make jane and peter friends:
insert into friends (user1, user2) values (
(select id from users where name='jane'),
(select id from users where name='peter')
);
select u1.name, u2.name
from users u1
join friends f on u1.id=f.user1
join users u2 on f.user2=u2.id;
+------+-------+
| name | name |
+------+-------+
| jane | peter |
+------+-------+
1 row in set (0.00 sec)
现在,这取决于你是否希望你的友谊是对称的(即Jane/Peter<=>Peter/Jane)。如果是这样,则friends
表中需要两个条目。
您必须创建两个saprate表来处理多个好友条目,如下所示。。
表"user"user_id用户名…
表"朋友"id用户_id_1用户_id_2…
您必须定义每个用户的id(只要所有用户名都是唯一的,用户名就可以作为id使用),称为主键
然后定义另一个名为friends的表,该表将包括类似的行
用户名|好友名称用户名|好友名
这种类型的结构被称为一对多关系。
表格图片说明了母子关系
users table friends table
id username row_id user friend
1 ali 1 ali khurram
2 khurram 2 ali tazeen
3 tazeen 3 ali babar
4 babar 4 khurram ali
5 khurram babar