Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After having a look at the <a href="http://dev.mysql.com/doc/refman/5.0/en/subqueries.html" rel="nofollow">subquery documentation</a> I have managed to come up with a working solution.</p> <p>In this example A has a <code>members.id=8</code>.</p> <pre><code>SELECT * FROM members WHERE id IN ( SELECT m.id FROM friends f INNER JOIN members m on m.id=f.uid WHERE f.friend_uid IN ( SELECT m.id FROM friends f INNER JOIN members m on m.id=f.uid WHERE f.friend_uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 UNION SELECT m.id FROM friends f INNER JOIN members m on m.id=f.friend_uid WHERE f.uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 ) AND m.id&lt;&gt;8 AND f.confirmed_uid=1 AND f.confirmed_friend_uid=1 UNION SELECT m.id FROM friends f INNER JOIN members m on m.id=f.uid WHERE f.uid IN ( SELECT m.id FROM friends f INNER JOIN members m on m.id=f.uid WHERE f.friend_uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 UNION SELECT m.id FROM friends f INNER JOIN members m on m.id=f.friend_uid WHERE f.uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 ) AND m.id&lt;&gt;8 AND f.confirmed_uid=1 AND f.confirmed_friend_uid=1 ) AND id NOT IN ( SELECT m.id FROM friends f INNER JOIN members m on m.id=f.uid WHERE f.friend_uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 UNION SELECT m.id FROM friends f INNER JOIN members m on m.id=f.friend_uid WHERE f.uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 ); </code></pre> <p>This query runs nice and fast and returns friends of all A's friends, that are not already friends of A. It also ensure that friendships have been confirmed by both members in the relationship.</p> <p>There may well be a way to reduce the size of this query, as the same <a href="http://dev.mysql.com/doc/refman/5.0/en/subqueries.html" rel="nofollow">subquery</a> is used on three separate occasions in the query as a whole.</p> <pre><code> SELECT m.id FROM friends f INNER JOIN members m on m.id=f.uid WHERE f.friend_uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 UNION SELECT m.id FROM friends f INNER JOIN members m on m.id=f.friend_uid WHERE f.uid=8 AND confirmed_uid=1 AND confirmed_friend_uid=1 </code></pre> <p>If there is a way to only run this subquery once, please let me know. Otherwise I will edit the answer if/when I figure it out myself.</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.
 

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