当我有一张桌子时users
:
id | login
1 Mike
2 Janet
3 Bruce
我有一张友谊表,叫做friendlist
:
id | user | friend
1 1 2 // Mike is friend with Janet
2 2 1 // Janet accepted, created the friendship!
3 1 3 // Mike is friend with Bruce
4 3 1 // Bruce accepted!
现在,迈克有2 个朋友,珍妮特有1 个,布鲁斯有1 个。
我要运行什么查询来计算这样的朋友数量?
这不是家庭作业。我已经为此苦苦挣扎了几个小时,无法做到这一点。
一个对我有用的查询,但返回不正确的结果(比实际朋友更多):
SELECT `users`.`id`, `login`, COUNT(`a`.`id`)
FROM `users`
LEFT JOIN(
SELECT user AS `id` FROM `friendlist`
UNION ALL
SELECT friend FROM `friendlist`
) as `a` ON `a`.`id` = `users`.`id`
GROUP BY `users`.`id`