简体   繁体   中英

How to return count of sub-query results as column in mysql

I have a table called users with a primary key called user_id for each user.

I have another table called friends which link users to other users as friends.

This friends table has two columns user_id and friend_id. The user_id column is always the lower of the two user_id's in order to prevent duplicates.

I want to do a query to get all the fields from the users table, but also return how many mutual friends a user has with another user as a count in another column called mutual_friends_count.

So basically if i wanted to know how many mututal friends each user has in common with user_id 5, the query would select all from the users table and for each user do a subquery to find the mutual friends and return the count as mutual_friends_count

It's not beautiful but it does the trick..

SELECT `u`.`user_id`, `f`.`friend_id`, `m`.`mutualFriends`
FROM `users` as `u`, `friends` as `f` 
JOIN (
   SELECT COUNT(*) as `mutualFriends`, `users`.`user_id`
   FROM `users`, `friends` 
   WHERE `friends`.`user_id` = `users`.`user_id` 
   GROUP BY `users`.`user_id`
   ) as `m` 
   ON `m`.`user_id` = `f`.`friend_id` 
WHERE `f`.`user_id` = `u`.`user_id` 
AND `u`.`user_id` = 5;

Not sure if this is the simplest or most efficient way of doing what you want, but it works:

select u.user_id, count(1)
from users u
join friends f on f.user_id = u.user_id or f.friend_id = u.user_id
join friends mutual on (mutual.user_id = 5 and mutual.friend_id = f.friend_id and mutual.friend_id != u.user_id) or (mutual.friend_id = 5 and mutual.user_id = f.user_id and mutual.user_id != u.user_id)
where u.user_id != 5
group by u.user_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM