1

For a social network site, I have a table with the ids of the inviter and the invitee and the status of the invitation ie accepted or not. According to what I've read, this seems to be best practice for a friends table.

Table friends

id | inviterid |inviteeid |status

however, for a given userid, I want to display all the "friends" the person has including their names. I can get a list of records of relationships with a simple query

Select * from friends WHERE inviterid = '33' or inviteeid = '33'"

But, this does not translate easily into a list of friends, since the friends could be either inviters or invitees so the field will be different depending on who invited whom.

Is there a better table design for a friends table? Alternatively, is there a sql syntax that would select friends who can be either inviters and invitees. Ultimately, I need to do a join to another table that has the users names.

4

3 回答 3

0

您有一个包含以下列的用户表

userId|name|...

和你的朋友桌

id | inviterid |inviteeid |status

如果您想查找该用户邀请主题的用户的朋友,您可以使用以下查询!

select id, status from friend_tbl inner join user_tbl on user_tbl.id=friend_tbl.inviterid;

或者,如果您想获得该用户的朋友主题邀请他/她,您可以使用以下查询:

select id, status from friend_tbl inner join user_tbl on user_tbl.id=friend_tbl.inviteeid;

我希望这些可以帮助你,我能理解你的目的!

于 2012-08-02T01:35:24.140 回答
0

使用 union 将两种friendS放在一起,然后可以将结果与username表连接起来。

Select inviterid as friend_id, status from friends where inviteeid = 33
Union
Select inviteeid as friend_id, status from friends where inviterid =33
于 2012-08-02T01:37:29.527 回答
0

对于这种情况,我个人更喜欢有两张桌子,朋友桌和邀请桌

朋友桌

id | userid | friendid

所以选择朋友只是

SELECT friendid FROM friend_table WHERE userid = 33

邀请表

id | inviterid | inviteeid | status

用于在用户批准后更改邀请表的状态,并在朋友表中插入新行

UPDATE invite_table SET status = 'accepted' WHERE inviterid = 33
INSERT INTO friend_table (`userid`, `friendid`) VALUES (33, $friendid)
于 2012-08-02T01:50:22.900 回答