gpt4 book ai didi

MySQL:选择我关注的人和关注我的人

转载 作者:行者123 更新时间:2023-11-29 04:42:14 26 4
gpt4 key购买 nike

我有一个非常简单的表 - follow - 我在其中存储关注者。

user | following
-----------------
1 | 3

以上表示用户 1 正在关注用户 3。

问题:我想选择所有关注用户 3 的人,并且我想查看用户 3 是否关注他们。

下面的查询满足了我的要求,但它列出了所有用户,而我只想要关注用户 3 的用户。我已经尝试了各种方案,但今天我却无法理解逻辑。这是我所能得到的最接近的结果。

SELECT 
u.id,u.username
,u.avatar
,f.*
FROM
users u
LEFT JOIN follow f
ON f.following=u.id and f.user=3

最佳答案

我将从关系开始。您想要用户 3 的所有关注者,因此从 follow 表开始并选择那些 following = 3 的记录。

然后您可以加入users 表来获取这些用户的信息。这可以是内部联接,因为您需要这些记录,如果用户 3 没有任何关注者,则不需要返回任何内容。

然后再加入follow,看看另外一个方向有没有类似的关系。我将其设为左连接,因此您可以检查是否找到了该记录。

如果您只需要关注用户 3 并且也被关注的那些用户的列表,您可以简单地将此联接更改为内部联接。

SELECT 
u.id,
u.username,
u.avatar,
case when b.user is null then -- No record in b if 3 didn't follow this user back.
'User is not following back'
else
'User is following back'
end as back
FROM
follow f -- IDs of followers of user 3
INNER JOIN users u -- User information of those followers
ON u.id = f.user
LEFT JOIN follow b -- Check if 3 follows them back.
ON b.user = f.following and
b.following = u.id
WHERE
f.following = 3

如果您需要用户 3 自己的用户信息,您可以针对 f 第二次内部加入 users 表(使用不同的别名),但我会使用一个单独的查询。

关于MySQL:选择我关注的人和关注我的人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953972/

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