The following are three MySQL queries. The first returns everything that I am looking for in one query, and in the second - the same aggregation results, but in two queries.
I am wondering why a single request takes 2 to 100 seconds longer when it seems that the process time should be equivalent between all three requests. Is there a way to optimize a single query to work as fast as separate queries? Adding more ORs inside the WHERE clause for a single query does not increase the process time, but I have cases where I need to do many more ORs and, ultimately, one query will be as fast as executing ten individual queries.
It seems that a single request gets cached after it is launched and may take minutes to run for the first time, while single requests always complete within the same timeframe.
Can multiple columns matter here?
It should be noted that the table does not have an identifier field as a primary index. Does this cause this unwanted behavior?
It is hard to run the tests here, as the table contains one hundred million rows, and adding columns and indexes takes close to the day.
SINGLE QUERY (4.2s)
SELECT name_id FROM staging_company_search WHERE (name_word_0 = 'the' AND name_word_1 = 'glazier') OR (name_word_0 = 'bridgewaters' AND name_word_1 = '');
EQUIVALENT AGGREGATE QUALIFICATIONS (0.8 s each )
SELECT name_id FROM staging_company_search WHERE name_word_0 = 'the' AND name_word_1 = 'glazier'; SELECT name_id FROM staging_company_search WHERE name_word_0 = 'bridgewaters' AND name_word_1 = '';
EXPLAIN ON THIS QUERIES
id select_type table type possible_keys key key_len ref rows extra 1 SIMPLE staging_company_search range name_word_0,name_word_1 name_word_0 102 NULL 2197605 Using index condition; Using where 1 SIMPLE staging_company_search ref name_word_0,name_word_1 name_word_1 102 const 128 Using index condition; Using where 1 SIMPLE staging_company_search ref name_word_0,name_word_1 name_word_0 102 const 33 Using index condition; Using where
DATABASE DIAGRAM
CREATE TABLE `staging_company_search` ( `name_id` int(11) unsigned NOT NULL DEFAULT '0', `name_word_0` varchar(100) NOT NULL, `name_word_1` varchar(100) NOT NULL, KEY `name_id` (`name_id`), KEY `name_word_0` (`name_word_0`), KEY `name_word_1` (`name_word_1`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;