简体   繁体   中英

Get mutual friends from Facebook friends (MySQL table)

I'm trying to get mutual friends between 2 people. I've saved the persons friends in a table called "friends" with the following fields:

id | facebook_id | name | uid | timestamp

  • id = unique id for the record
  • facebook_id = the friends facebook id
  • name = the friends name
  • uid = the users uid on my site, which is a friend to the person saved in the table
  • timestamp = don't need to explain :-)

Hope it make sense, have tried various ways to get the friends, but without luck

I dont know if using subqueries would be faster or mySQL already optimizes it. Solution with subqueries:

  SELECT f1.id, f1.name 
  FROM (SELECT id, name FROM friends WHERE uid=1) f1 
  JOIN (SELECT id, name FROM friends WHERE uid=2) f2 
  ON f1.id=f2.id;

It would be nice if MySQL has an INTERSECT operator, but...

You can grab all the friends of one person:

SELECT id, name
FROM friends
WHERE uid = 1

You could then JOIN this list back to the friends table, looking for the same friend for the other user:

SELECT f1.id, f1.name
FROM friends f1
  JOIN friends f2 on f1.id = f2.id
WHERE f1.uid = 1
and f2.uid = 2

It's pseudo-code, but it should be close.

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