Mysql 同表选择好友请求

Mysql 同表选择好友请求,mysql,sql,database,database-design,Mysql,Sql,Database,Database Design,我正在写一个聊天数据库。 如果用户是朋友,那么他们在friends表中有彼此,就像my tablesee链接中的用户1和2或1和5一样。 但我想知道是谁以朋友的身份发送了申请。在这种情况下,只有一个人存储另一个人的id,比如发送用户7请求的用户1。 我有一张桌子: 只有3列:idfriend、iduser、friend\u id 如何选择发送好友请求的用户id friend\u id? 如果选择用户1,则我的sql必须返回此好友请求: |朋友身份证| 七, 我试试这个: select frie

我正在写一个聊天数据库。 如果用户是朋友,那么他们在friends表中有彼此,就像my tablesee链接中的用户1和2或1和5一样。 但我想知道是谁以朋友的身份发送了申请。在这种情况下,只有一个人存储另一个人的id,比如发送用户7请求的用户1。 我有一张桌子:

只有3列:idfriend、iduser、friend\u id

如何选择发送好友请求的用户id friend\u id? 如果选择用户1,则我的sql必须返回此好友请求:

|朋友身份证|

七,

我试试这个:

select friend.friend_id from friend inner join friend as friends on 
friend.iduser != friends.friend_id and friends.iduser != friend.friend_id  
and friend.iduser != friends.iduser and friend.friend_id != 
friends.friend_id where friend.iduser = 1
但选择7、2和5。只需要7个,不存在:

select t.friend_id from friend t
where t.iduser = 1 
and not exists (
  select 0 from friend
  where iduser = t.friend_id and friend_id = t.iduser 
)
看。 结果:


希望这就是您正在寻找的解决方案:

select t1.iduser, t1.friend_id
from friends t1
where t1.friend_id not in
(
select t2.iduser
from friends t2
where t2.friend_id = t1.iduser
)

字段idfriend是自动递增的。别理他。你的问题不清楚。将结果集显示为表格。谢谢,它很有效!你能告诉我我应该用什么样的sql来查找朋友,比如用户1-2和1-5吗?我不明白你的意思。此代码适用于1个用户。如果您想要多个用户的结果,请将其中的t.iduser=1更改为类似于1、3中的where t.iduser。5不,我是说a如何找到朋友1的所有朋友,例如,从friend中选择friend\u id,其中iduser=1如果friends是指存在于两列中的id,则使用exists。从friend t1中选择t1.friend\u id,其中t1.friend\u id不在,从friend t2中选择t2.iduser,其中t2.friend\u id=t1.iduser和t1.iduser=1谢谢!
select t1.iduser, t1.friend_id
from friends t1
where t1.friend_id not in
(
select t2.iduser
from friends t2
where t2.friend_id = t1.iduser
)