简体   繁体   English

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

[英]How can I show mutual relation between two users in database?

I'm trying to show relation between two users. 我试图显示两个用户之间的关系。 I want to insert only one row to Relations table (see structure below) . 我只想在Relations表中插入一行(请参见下面的结构) But my script is showing that user B is friend of himself - that's not right. 但是我的脚本显示用户B是他自己的朋友-这是不对的。

This is a structure of my database (with examples) : 这是我的数据库的结构(带有示例)

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)

What am I doing wrong? 我究竟做错了什么? Here's my query: 这是我的查询:

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

I recommend to insert two rows into Relations table. 我建议在“ Relations表中插入两行。

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

For example, user A send friend request to B. Until B accept this request, the status of both rows would be 0 . 例如,用户A向B发送朋友请求。在B接受该请求之前,两行的status均为0

Query for accepting: (user B) 查询接受:(用户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)

Query for selecting: 查询选择:

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

Update: If you really want to insert only one row, you would need to execute two queries - the one for the friends user B added and another one for the friends that has added User B to their friend list. 更新:如果您确实只想插入一行,则需要执行两个查询-一个查询用于添加用户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

Your problem is that you're selecting friend_id which means that if you execute your query as user B, the friend_id would be 2 - user B. (see your table example) 您的问题是您选择的是friend_id,这意味着如果您以用户B的friend_id执行查询,则friend_id将为2-用户B。 (请参见表示例)

You should take a look to this question for more information about performance. 您应该查看此问题以获取有关性能的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM