Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgresql select people you may know orderded by number of mutual friends
    primarykey
    data
    text
    <p>I'm building a social network, and I want my members to be able to easily find new friends. Just like in Facebook, I want to suggest them some people they may know by the number of mutual friends they have.</p> <p>My PostgreSQL database structure for friendships is as following:</p> <pre><code>&gt; PROFILES_FRIENDSHIPS &gt; ---------------------- &gt; - fri_profile_from // int, Person who sent the friendship request &gt; - fri_profile_to // int, Person who received the friendship request &gt; - fri_accepted // tinyint, has the person accepted the friendship request? </code></pre> <p>This is the query I figured out in PostgreSQL for finding the number of mutual friends between 2 profiles (profile with ID 24, and profile with ID 26):</p> <pre><code>SELECT COUNT(*) FROM profiles AS p INNER JOIN ( SELECT ( CASE WHEN ( 26 = f.fri_profile_from ) THEN f.fri_profile_to ELSE f.fri_profile_from END) AS fri_profile_from FROM profiles_friendships AS f WHERE 1 = 1 AND (f.fri_profile_to = 26 OR f.fri_profile_from = 26) AND fri_accepted = 1) AS f1 ON (f1.fri_profile_from = p.pro_id) INNER JOIN ( SELECT ( CASE WHEN ( 24 = f.fri_profile_from ) THEN f.fri_profile_to ELSE f.fri_profile_from END) AS fri_profile_from FROM profiles_friendships AS f WHERE 1 = 1 AND (f.fri_profile_to = 24 OR f.fri_profile_from = 24) AND fri_accepted = 1) AS f2 ON (f2.fri_profile_from = p.pro_id) </code></pre> <p>Now I have been trying to convert this query to make it find the profiles with the most mutual friends of me, but who are not friends with me. But without success... I also researched a lot of examples on this website, but most them are working with double records in the friendships table. Like if 24 is friends with 26, there are 2 records: (24, 26) and (26, 24). That makes them easier to join and to find mutual friends, but that's not how I want to build my database.</p> <p>If someone could help me to get started on this query, I would be very grateful.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload