I have a MySQL table for users with the primary key _id, and I want to present friendship (visibility in the friends lists of other users) as a table with userId foreign key pairs. I think something like:
CREATE TABLE UserFriendships (
userIdA INT NOT NULL,
userIdB INT NOT NULL,
PRIMARY KEY (userIdA, userIdB),
FOREIGN KEY (userIdA) REFERENCES Users(_id)
FOREIGN KEY (userIdB) REFERENCES Users(_id)
)
I understand that this will allow you to insert both (userIdA = 2, userIdB = 7), and (userIdA = 7, userIdB = 2)as separate lines. I want one line per friendship, that is, one line per userIds pair.
Does anyone know how I can improve this? Even if the above limitation is performed to obtain a list of all the user's friends foo, I have to make the union, something like: SELECT userIdB AS friendUserId WHERE userIdA = foo UNION SELECT userIdA WHERE userIdB = foo. Is this the best way to fulfill this request, or should I think about changing my schema?