MySQL Query to find friends and number of mutual friends

前端 未结 3 406
盖世英雄少女心
盖世英雄少女心 2020-12-28 11:16

I have looked through the questions but I cant find anything that does exactly what I need and I can\'t figure out how to do it myself.

I have 2 tables, a user table

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 12:04

    This query lists anyone who's not friend with user 1 and whose surname matches '%bloggs%':

    SELECT
      users.user_id,
      users.first_name,
      users.surname,
      Sum(IF(users.user_id = friend_links_1.friend_id, 1, 0)) As mutual
    FROM
      users inner join
        (friend_links INNER JOIN friend_links friend_links_1
         ON friend_links.friend_id = friend_links_1.user_id)
      ON friend_links.user_id=1 AND users.user_id<>1
    WHERE
      users.surname LIKE '%bloggs%'
    GROUP BY
      users.user_id, users.first_name, users.surname
    HAVING
      Sum(IF(users.user_id = friend_links.friend_id, 1, 0))=0
    

    just change the user id on the ON clause, and the surname on the WHERE clause. I think it should work correctly now!

提交回复
热议问题