问题
在子查询中的users.user_id中,它是未知的 并且它在主查询中的定义与它们之间没有关系
任务是:
找到user2朋友+与user1相互计数
mysql找到user2好友并与user1获得mutual_count(与每个user2好友)
表用户
user_id | username
------------------
1 | user1
2 | user2
3 | user3
4 | user4
5 | user5
表朋友
user_one_id | user_two_id
------------------------
1 | 2
1 | 4
2 | 3
2 | 4
3 | 1
5 | 2
预期输出//(user2朋友:使用user1检查结果user_id以获得相互计数)
user_id | mutual_count
------------------------
1 | 2 // user1 and user1 mutual users(user2,user3,user4)
3 | 1 // user3 and user1 mutual users(user2)
4 | 1 // user4 and user1 mutual users(user2)
5 | 0 // user5 and user1 -> No mutual users
mysql语句
SELECT users.user_id,
(SELECT count(a.friendID) FROM
( SELECT user_two_id friendID FROM friends WHERE user_one_id = users.user_id
UNION
SELECT user_one_id friendID FROM friends WHERE user_two_id = users.user_id
) AS a
JOIN
( SELECT user_two_id friendID FROM friends WHERE user_one_id = 1
UNION
SELECT user_one_id friendID FROM friends WHERE user_two_id = 1
) AS b
ON a.friendID = b.friendID
) as mutual_count
FROM friends LEFT JOIN users
ON friends.user_one_id = users.user_id or friends.user_two_id = users.user_id
WHERE (friends.user_one_id = 2 OR friends.user_two_id = 2) AND users.user_id != 2
我得到的错误 未知栏' users.user_id'在' where子句' 获取mutual_count canot的问题子查询知道users.user_id
任何帮助表示赞赏