What I ended up doing was taking two SQL queries and using the array_intersect() in PHP to filter out the results:
$sql1 = 'SELECT z.*, u.username, u.user_colour, u.username_clean, u.user_avatar, u.user_avatar_type
FROM ' . ZEBRA_TABLE . ' z, ' . USERS_TABLE . ' u
WHERE (( z.user_id = ' . $user->data['user_id'] . '
AND z.friend = 1
AND u.user_id = z.zebra_id )
OR ( z.zebra_id = ' . $user->data['user_id'] . '
AND z.friend = 1
AND u.user_id = z.user_id ))
ORDER BY u.username_clean ASC';
$sql2 = 'SELECT z.*, u.username, u.user_colour, u.username_clean, u.user_avatar, u.user_avatar_type
FROM ' . ZEBRA_TABLE . ' z, ' . USERS_TABLE . ' u
WHERE (( z.user_id = ' . $user_id . '
AND z.friend = 1
AND u.user_id = z.zebra_id )
OR ( z.zebra_id = ' . $user_id . '
AND z.friend = 1
AND u.user_id = z.user_id ))
ORDER BY u.username_clean ASC';
The structure of both queries are the same and the only difference is $user->data['user_id] (first person) is replaced with $user_id (second person) in the second query. I want to retrieve friends that both users have in common. Could anyone merge this into a single query so that I don’t have to use two queries and call array_intersect()?
Well, you could always just subquery both:
You may want to add
u.user_idto the field list of both queriesu.user_id AS u_user_idthen change the second join clause froma.username = b.usernametoa.u_user_id = b.u_user_id…EDIT: Now that I really look at it closer, those two queries are almost identical… Why not just do something like this (replace the where clause to this):
That should give you the result of both queries intersected, and be faster since it can optimize better (hopefully)…
Oh, and they are in different where blocks because there’s a few cases where
z.user_idmatches$user_id, butz.zebra_idmatches$user->data['user_id']… So rather than list all the permutations, I just layed it out like this…