I have a friend table on a social type network I am building with this structure:
uid binary(16)
memberid int
friendid int
datefriended datetime
isactive bool
This way I have relationships and other data stored in one table only. But say I need to get all my friends, whether I am the friender( memberid ) or I am the friendee( friendid ) then I need to get the user names from the members table. The query is this:
SELECT m.name FROM members m
INNER JOIN friends f on m.memberid = f.friendid
WHERE f.memberid = 1
UNION ALL
SELECT m.name from members m
INNER JOIN friends f on m.memberid = f.memberid
WHERE f.friendid = 1
This to me seems like it could be a resource intensive call to the db if you have lots of users and friends pulling this data. I know there is the option to have a pair of entries for each friend relationship but I’m trying to do this in once query.
Do you have any thoughts on how to improve the query or table structures to increase performance. Or maybe it won’t be as bad as I am foreseeing?
In addition to my comment above advising you to create indexes on
friends.memberid,friends.friendidandmembers.memberid, you don’t need theUNIONat all: