Here is my query:
SELECT COUNT(`id`)
FROM `comments`
WHERE
`user_id` != '1' -- Author does not need to know about his own comments
AND (
`article_id` IN (4, 2476, 14954, 83981, 83982)
OR `request_id` IN (3, 5, 7)
);
And the table:
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`part_id` int(11) DEFAULT NULL,
`article_id` int(11) DEFAULT NULL,
`request_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`name` varchar(500) DEFAULT NULL,
`comment` text,
`add_date` int(11) DEFAULT NULL,
`ip` text,
PRIMARY KEY (`id`),
KEY `key_article_id_add_date` (`article_id`,`add_date`),
KEY `key_part_id_add_date` (`part_id`,`add_date`),
KEY `add_date` (`add_date`),
KEY `request_id` (`request_id`),
KEY `user_id` (`user_id`,`article_id`,`request_id`)
) ENGINE=innodb AUTO_INCREMENT=3536452 DEFAULT CHARSET=utf8
No matter how I try and what index I add, mysql perferrs to scan all 3039138 rows and query takes forewer. Here is the EXPLAIN output:
+----+-------------+----------+------+--------------------------------------------+------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+------+--------------------------------------------+------+---------+------+---------+-------------+
| 1 | SIMPLE | comments | ALL | key_article_id_add_date,user_id,request_id | NULL | NULL | NULL | 3039138 | Using where |
+----+-------------+----------+------+--------------------------------------------+------+---------+------+---------+-------------+
If I remove one of confitions (user_id, article_id or request_id) mysql seems to have no problems using indexes, but with all the 3 of them – nothing helps.
Any ideas how I can index comments table so mysql could use an index on this query? Or is there any other solution to improve this query performance.
First check the current execution plan for this query and identify whether its using the key you have created for those three columns. If it is not using that particular index, then force the sql to use that index like below
Please replace user_id_corresponding_idex_name with corresponding name of non-clustered index created for user_id key in your table.
http://dev.mysql.com/doc/refman/4.1/en/index-hints.html