如何在数据库中显示两个用户之间的相互关系?

时间:2015-07-18 14:38:36

标签: php mysql

我试图显示两个用户之间的关系。我想只向Relations插入一行(参见下面的结构)。但我的剧本显示用户B是他自己的朋友 - 那不对。

这是我的数据库(带示例)的结构

Users
id|email|password|name|pic_url|friend_count
1 |a@.. |aaaaaaaa|A   |http...|1
2 |b@...|bbbbbbbb|B   |http...|0

Relations
id|user_id|friend_id|status(0 and 1)
1 |1      |2        |1(if accepted)

我做错了什么?这是我的疑问:

SELECT Relations.friend_id, Users.name,Users.email,Users.pic_url FROM Relations
INNER JOIN Users
ON Relations.friend_id = Users.id

WHERE  Relations.user_id = $user_id
OR Relations.friend_id = $user_id
AND Relations.status = 1

1 个答案:

答案 0 :(得分:1)

我建议在Relations表中插入两行。

id|user_id|friend_id|status(0 and 1)
1 |1      |2        |1(if accepted)
2 |2      |1        |1(if accepted)

例如,用户A向B发送好友请求。在B接受此请求之前,两行的status都为0

查询接受:(用户B)

UPDATE Relations SET status=1 WHERE (user_id=$user_id AND friend_id=$friend_id) OR (user_id=$friend_id AND friend_id=$user_id)

查询选择:

SELECT Relations.friend_id, Users.name, Users.email, Users.pic_url FROM Relations
    INNER JOIN Users
    ON Relations.friend_id = Users.id

    WHERE Relations.user_id = $user_id
    AND Relations.status = 1

更新:如果您确实只想插入一行,则需要执行两个查询 - 一个用于添加好友用户B,另一个用于已添加用户B的好友他们的朋友名单。

SELECT Relations.friend_id, Users.name, Users.email, Users.pic_url FROM Relations
    INNER JOIN Users
    ON Relations.friend_id = Users.id

    WHERE Relations.user_id = $user_id
    AND Relations.status = 1

SELECT Relations.user_id, Users.name, Users.email, Users.pic_url FROM Relations
    INNER JOIN Users
    ON Relations.user_id = Users.id

    WHERE Relations.friend_id = $user_id
    AND Relations.status = 1

您的问题是您选择了friend_id,这意味着如果您以用户B执行查询,friend_id将为2 - 用户B. (请参阅您的表格示例)

您应该查看this question以获取有关效果的更多信息。