gpt4 book ai didi

mysql - 如何创建友情关系sql(mysql)?

转载 作者:行者123 更新时间:2023-11-29 17:34:47 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com