This may have been asked before and I just do not know the way to search for it. I think this should be basic but I can’t figure it out.
I have a friends table that is formatted as below:
id toid fromid
1 45 50
2 50 45
3 46 45
4 45 46
5 40 45
The member logged in is $member_number…which in this case is “45”.
The "toid" and "fromid" fields correspond to member IDs. If the member “45” is logged in, how would I write a SELECT query to get all the members that they are friends with?
In order for them to be friends there has to be reciprocating friend rows. For example, in the above, members 45 and 50 are friends because they friend records going to and from (in rows 1 and 2). The same can be said of 45 and 46 as shown in rows 3 and 4. But, 40 and 45 are not friends because there are not reciprocating rows.
So the result of the Select statement should be… 50, 46.
You could use a union of two selects, like this
union has the extra benefit of filtering out duplicates so in your example 50 won’t show up twice.
Make sure both toid and fromid are indexed (individually or as the left most part of another index) and this query will go lightning fast.
Also, there is no need for the id column (in my opinion), you put a primary key on toid and fromid and that is enough to identify any row in this table.
An example can be seen at SQLFiddle