关注我在SQL中关注的用户
的表
id | name
---------
1 | John
2 | Mark
3 | Bill
4 | Steve
5 | Jeff
我有两个名为用户
和fans
代码>表:
fan | user
1 | 2
1 | 5
2 | 3
2 | 4
2 | 5
“ fan”是关注用户的用户,“用户”是正在关注的用户。现在,如果我们将约翰(ID 1)作为当前用户,并且鉴于John正在关注Mark(ID 2),那么我们如何获得约翰所关注的每个人的以下内容,而不是约翰已经关注的人(在John遵循Mark遵循用户3、4和5的标记,但由于John已经关注用户5,只能返回3和4。我尝试使用运算符中的进行此操作,但我不确定它会随着更多条目而缩小。任何帮助将不胜感激。
I have two tables called users
and fans
.
The users
table looks like this:
id | name
---------
1 | John
2 | Mark
3 | Bill
4 | Steve
5 | Jeff
And this is the fans
table:
fan | user
1 | 2
1 | 5
2 | 3
2 | 4
2 | 5
"Fan" is the user who is following the user and "user" is the one who is being followed. Now If we take John (id 1) as the current user, and given that John is following Mark (id 2), How can we get the following of everyone whom John is following, but not the ones whom John is already following (In this case John is following Mark. Mark is following user 3, 4 and 5 but only 3 and 4 should be returned because John is already following user 5.)? I tried doing this with the IN
operator but I am not sure it would scale well with more entries. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须加入多个
fans
的副本:如果您还想要用户的名称:
将
?
更改为您想要的用户的ID。请参阅<
a href =“ https://dbfiddle.uk/?rdbms = mysql_5.7&amp; fiddle = E3532158D379E5BC275345E26A5EB44”
You must join multiple copies of
fans
:If you want the names of the users also:
Change
?
to the id of the user that you want.See the demo.
如果我正确理解,您可以尝试加入
用户
和fans
以查找遵循的人,然后两次加入或使用自加入用户两次
sqlfiddle
If I understand correctly, you can try to join
users
andfans
to find who is followed user then do joinor using self-join user twice
sqlfiddle