I have two tables: User and User2Friend. I need to get user’s friends. Query should handle two columns as FriendId: FriendId and UserId because we don’t know who added whom. In result both are friends.
The query:
SELECT DISTINCT
`Id`
, `UserName`
FROM `User`
WHERE `Id` IN
(SELECT
IF(`UserId` = 25, `FriendId`, `UserId`) -- This important part - friends are always mutual
FROM `User2Friend`
WHERE `UserId` = 25
OR `FriendId` = 25)
LIMIT 10
The schema:
CREATE TABLE `User` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserName` varchar(16) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `User2Friend` (
`Id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`UserId` int(10) unsigned NOT NULL,
`FriendId` int(10) unsigned NOT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `UserIdFriendId` (`UserId`, `FriendId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If user A added user B as friend, user B appears in user A friend list, after that user B must have user A in friend list too. I don’t really like subquery approach because I cannot use LIMIT in sub-select.
I’m expecting few millions of users, so performance is important.
Do you think it would be better to split this query to two separate ones?
Or maybe I need to have tricky JOIN?
Okay! I have split it to two queries…