Optimizing slow query in MySql InnoDB Database

640 views Asked by At

I have a MySql database with a query that is running really slow. I'm trying the best I can to make it perform better but can't see what I'm doing wrong here. Maybe you can?

CREATE TABLE `tablea` (
    `a` int(11) NOT NULL auto_increment,
    `d` mediumint(9) default NULL,
    `c` int(11) default NULL,
    PRIMARY KEY  (`a`),
    KEY `d` USING BTREE (`d`)
) ENGINE=InnoDB AUTO_INCREMENT=1867710 DEFAULT CHARSET=utf8;

CREATE TABLE `tableb` (
    `b` int(11) NOT NULL auto_increment,
    `d` mediumint(9) default '1',
    `c` int(10) NOT NULL,
    `e` mediumint(9) default NULL,
    PRIMARY KEY  (`b`),
    KEY `c` (`c`),
    KEY `d` (`d`),
) ENGINE=InnoDB AUTO_INCREMENT=848150 DEFAULT CHARSET=utf8;

The query:

SELECT tablea.a, tableb.e
FROM tablea
INNER JOIN tableb ON (tablea.c=tableb.c) AND (tablea.d=tableb.d OR tableb.d=1)
WHERE tablea.d=100

This query takes like 10 seconds to run if tablea.d=100 gives 1500 rows and (tablea.d=tableb.d OR tableb.d=1) gives 1600 rows. This seems really slow. I need to make it much faster but I can't see what I'm doing wrong.

MySql EXPLAIN outputs:

id   select_type table   type   possible_keys key key_len ref       rows  Extra
1    SIMPLE      tablea  ref    d             d   4       const     1092  Using where
1    SIMPLE      tableb  ref    c,d           c   4       tablea.c  1     Using where
1

There are 1 answers

0
ypercubeᵀᴹ On

If I am not confused by the OR, the query is equivalent to:

SELECT tablea.a, tableb.e
FROM tablea
  INNER JOIN tableb
    ON  tablea.c = tableb.c 
WHERE tablea.d = 100
  AND tableb.d IN (1,100) 

Try it (using EXPLAIN) with various indexes. An index on the d field (in both tables) would help. Perhaps more, an index on (d,c).