First of all your query is not very correct, proper versions should be:
SELECT *
FROM objects
INNER JOIN search
ON (objects.objectID = search.objectID and search.searchID = 1)
another version:
SELECT *
FROM objects
where objects.objectID in (
select search.objectID from search where search.searchID = 1)
They are absolutely the same from logic point of view, but I'm not sure that mysql will execute them in the same way, so test both and select fastest one
next issue about indexes:
- Do you really need to fetch * from table, maybe you can reduce to 1/2 columns?
- Do you really need varchar(255)? Try to reduce to actual strings length
- Create index on objects table: INDEXNAME (SORTCOLUMN, objectid, the rest of columns)
- Change table types to innodb,
- Increase
sort_buffer_size
andjoin_buffer_size
Now you can change your query to one of these (test both to select fastest)
SELECT *
FROM objects use index (INDEXNAME)
INNER JOIN search
ON (objects.objectID = search.objectID and search.searchID = 1)
order by SORTCOLUMN
or
SELECT *
FROM objects use index (INDEXNAME)
where objects.objectID in (
select search.objectID from search where search.searchID = 1)
order by SORTCOLUMN
this is what I'm getting on test db (explain extended is the same for both queries):
id type table type pk key key_len ref rows filter Extra
1 SIMPLE objects index srtcol 142 2091427 100.00 Using index
1 SIMPLE search eq_ref sid sid 5 const,testhash.objects.objectID 1 100.00 Using index
NOTE: if you need to have such long strings (varchar 255) - you can make a trick: add integer column, set it value according to proper order and make ordering and index on this column
here is my tables to test:
CREATE TABLE `objects` (
`objectID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sortcol` varchar(45) DEFAULT NULL,
PRIMARY KEY (`objectID`),
UNIQUE KEY `srtcol` (`sortcol`,`objectID`)
) ENGINE=InnoDB AUTO_INCREMENT=2490316 DEFAULT CHARSET=utf8;
CREATE TABLE `search` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`searchID` int(10) unsigned NOT NULL,
`objectID` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `sid` (`searchID`,`objectID`)
) ENGINE=InnoDB AUTO_INCREMENT=2162656 DEFAULT CHARSET=utf8;
each have approximately 2m random rows