我有一个 mysql 表:
friend (id,用户id, friend id)
和一个表 users (id, username) 例如:
(1,'John'), (2, 'Jerry'), (3, 'Larry), (4, 'Marry')
约翰和杰瑞是 friend ,所以我们有 friend
(1,2)
(2,2)
拉里请求约翰成为约翰的 friend ,但约翰没有接受
(3,1)
约翰向玛丽提出了请求,但玛丽没有接受
(1,4)
有没有办法执行 SQL 来为 John 的 friend 获取一些结果:
(1, Jerry)
在所有表中我们都有
(1,2)
(2,2)
(3,1)
(1,4)
最佳答案
select u.*
from friends f1
join friends f2 on f2.user_id = f1.friend_id
join users u on u.id = f1.friend_id
where f1.user_id = 1 -- John's id
将friends
表与其本身连接起来将确保“友谊”是“双向的”。
关于mysql - 如何创建友情关系sql(mysql)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374224/