Reputation: 324610
Please note that the database structure probably can't be changed without a lot of work due to the amount of users and data on it.
The "friends" table is basically like this:
> show create table `friends`
CREATE TABLE `friends` (
`id` int(10) unsigned NOT NULL auto_increment,
`user1` int(10) unsigned NOT NULL,
`user2` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user1_2` (`user1`,`user2`),
KEY `user1` (`user1`),
KEY `user2` (`user2`)
) ENGINE=InnoDB AUTO_INCREMENT=747908
To fetch a user's friends, I have three options:
user2
where user1
equals the user's ID, and vice versa, then combine the results in PHP.SELECT IF(user1=@userid,user2,user1) FROM friends WHERE @userid IN (user1,user2)
SELECT user2 FROM friends WHERE user1=@userid
UNION SELECT user1 FROM friends WHERE user2=@userid
I tried timing options 2 and 3, and this is where I have a problem: The first time I run it, option 2 takes about 400ms whereas option 3 only takes less then 1ms. Every other time, however, opton 2 takes 0.6ms and option 2 takes 0.8ms.
What should I do? Which option is actually faster? The EXPLAIN
queries return this:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE friends index NULL user1_2 8 NULL 386438 Using where; Using index
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY friends ref user1,user1_2 user1_2 4 const 8 Using index
2 UNION friends ref user2 user2 4 const 8
NULL UNION RESULT <union1,2> ALL NULL NULL NULL NULL NULL
Upvotes: 0
Views: 63
Reputation: 1061
As usual when benchmarking, beware of caches.
Measure your SELECT
queries using SQL_NO_CACHE
clause (see the SELECT
syntax).
Upvotes: 2