I have the following query:
SELECT DISTINCT c.id
FROM clients AS c
LEFT JOIN client_project AS cp ON (cp.client_id = c.id)
WHERE cp.project_id = 1
AND c.active_flag = 1
ORDER BY c.client_name
If I remove the order by, the query takes 0.005 seconds. With the order by, the query takes 1.8-1.9 seconds. I have an index on client_name
.
What else would improve the speed?
Edit: c.id is primary key, but there could be multiple records for it in client_project and therefore it may result in more than one record for each id. Also, removing the distinct makes 0.1 second difference in the query.
Addition: Here is my clients table:
CREATE TABLE IF NOT EXISTS `clients` (
`id` int(11) NOT NULL auto_increment,
...
`organization` varchar(255) character set utf8 collate utf8_bin NOT NULL,
`client_name` varchar(255) character set utf8 collate utf8_bin NOT NULL,
`active_flag` tinyint(1) NOT NULL,
...
PRIMARY KEY (`id`),
KEY `active_flag` (`active_flag`),
...
KEY `organization` (`organization`),
KEY `client_name` (`client_name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Using MySQL 5.0