【问题标题】:Optimizing slow query in MySql InnoDB Database优化 MySql InnoDB 数据库中的慢查询
【发布时间】:2011-02-10 14:09:21
【问题描述】:

我有一个运行非常缓慢的查询的 MySql 数据库。我正在尽我所能让它表现更好,但看不到我在这里做错了什么。也许你可以?

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;

查询:

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

如果 tablea.d=100 给出 1500 行并且 (tablea.d=tableb.d OR tableb.d=1) 给出 1600 行,则此查询需要大约 10 秒才能运行。这似乎真的很慢。我需要让它更快,但我看不出我做错了什么。

MySql 解释输出:

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

【问题讨论】:

  • 查看 c,d 上的复合索引是否有帮助。为什么 OR tableb.d=1 - 恕我直言,这会损害性能,请尝试使用 union 代替?
  • 发布“SHOW VARIABLES LIKE '%innodb%'”的输出。除了 Darhazer 的回答,看起来 InnoDB 默认配置设置已经到位。

标签: mysql optimization innodb acid


【解决方案1】:

如果我没有被OR弄糊涂的话,查询相当于:

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) 

尝试使用各种索引(使用EXPLAIN)。 d 字段(在两个表中)的索引会有所帮助。也许更多,(d,c) 上的索引。

【讨论】:

    猜你喜欢
    • 2013-06-02
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多