I have a MySQL table for Users with the primary key _id, and I want to represent friendships (visibility on friends lists of other users) as a table with pairs of userId foreign keys. I'm thinking 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)
)
It's my understanding that this will allow both (userIdA = 2, userIdB = 7)
and (userIdA = 7, userIdB = 2)
to be inserted as distinct rows. I want one row per friendship, that is to say one row per pair of userIds.
Does anyone know how I could improve this? Even if the above constraint is met, to get a list of all the friends of user foo I have to do a union, something like: SELECT userIdB AS friendUserId WHERE userIdA = foo UNION SELECT userIdA WHERE userIdB = foo
. Is this the best way to accomplish that query, or should I think about changing my schema?