你好,我说一个例子
我的关注表
A B 1 2 // same so its friend 2 1 // same so its a friend 1 3 // user 1 is following 3 1 4 // user 1 is following 4
等等
可以说我们是用户1我们如何列出我们的朋友?我脑子里有些东西
SELECT COUNT(*) FROM social WHERE ((A = B) = (B = A)) as friends // so it will be something like count friends where ( 1 = 2 ) = ( 1 = 2) if you get my logic
还是我们可以以某种方式做到这一点?
如果成功,它将计为1
这应该做到这一点:
SELECT COUNT(me.A) FROM social AS me INNER JOIN social AS you ON me.B = you.A WHERE me.A = you.B AND me.A = 1
COUNT如果需要朋友列表,请删除。
COUNT
编辑
根据要求,进行解释。
您正在JOIN对自己创建表,因为您对行之间的关系感兴趣。
JOIN
我决定将表别名为,me并you明确关系。这就是说专栏A可以将我称为 关注者 ,也可以将您称为关注者。列B是指 跟随者
me
you
A
B
如果要重命名列,查询将更清晰地显示
如果A->follower和B-> followee,我们将有:
follower
followee
SELECT COUNT(me.follower) FROM social AS me INNER JOIN social AS you ON me.followee = you.follower WHERE me.follower = you.followee AND me.follower = 1
就是说,获取此表的两个副本以及JOIN其中 me的跟随者是的关注者的行you。然后,通过捕获您希望拥有的愿望,过滤并仅显示跟随者所在的行me是you…的跟随者。(A == B) && (B == A)
(A == B) && (B == A)
也许表别名不是那么好,但是我希望可以澄清一下。
第二次编辑 根据下面的评论,更清晰的表格可能是:
SELECT COUNT(me.A) FROM social AS me INNER JOIN social AS you ON me.A = you.B AND me.B = you.A WHERE me.A = 1