我希望根据我们共同的朋友数量获得推荐给我的朋友列表。
这是我的架构:
我有一个users
表,它与follow_users
表有一对多的关系。
follow_users {
'follower_id', //many to one with users
'followee_id', //many to one with users
'is_approved'
}
如何编写一个查询,选择与我有多少共同朋友的用户?
修改
我想我越来越近了。我写了这个查询
$q = $this->em->createQuery("
select recUser, count(recUser.id) as recUserCount
from Zgh\FEBundle\Entity\User recUser
inner join recUser.followees recFollowUser
where recFollowUser.follower in (
select mutual.id
from Zgh\FEBundle\Entity\FollowUsers currentFollowUser
inner join currentFollowUser.followee mutual
where currentFollowUser.follower = :user
)
group by recUser.id
order by recUserCount desc
");
哪个返回我想要的用户,但也返回我已经关注过的用户,如何排除已经关注的用户?
(我已尝试在and recFollowUser.follower != :user
语句之后添加where
,但没有好处)
答案 0 :(得分:1)
此查询将获得给定:user_id
尚未结识的朋友的朋友的用户ID。该列表由共同的朋友排序。
SELECT fu2.follower_id
FROM follow_users fu
JOIN follow_users fu2
ON fu2.followee_id = fu.follower_id
AND NOT EXISTS (SELECT 1 FROM follow_users fu3
WHERE fu3.followee_id = :user_id
AND fu3.follower_id = fu2.follower_id)
WHERE fu.followee_id = :user_id
GROUP BY fu2.follower_id
ORDER BY COUNT(*) DESC