【问题标题】:MySQL looking up more rows than needed (indexing issue)MySQL 查找比需要更多的行(索引问题)
【发布时间】:2013-09-08 04:47:42
【问题描述】:

在我们的 MySQL 5.5 数据库中,我们有以下具有 30M+ 行的 InnoDB 表:

+----------------+-------------+-----------------+--------+
| participant_id | question_id | given_answer_id | status |
+----------------+-------------+-----------------+--------+
|       500      |      12     |        25       |    0   |
+----------------+-------------+-----------------+--------+

participant_id + question_id + given_answer_id 的组合是唯一的。

目前我们有以下键

主键(按此顺序)

  • participant_id
  • question_id
  • given_answer_id

索引键

  • question_id

对于这个表,我们的应用中有两种选择查询

[...] WHERE participant_id = x AND question_id = y AND given_answer_id = z;

[...] WHERE question_id = x;

通常,每个参与者 ID 都有 0 到

当我们执行以下查询时,它会显示 32096 行在哪里查找:

EXPLAIN SELECT * FROM example WHERE question_id = 500;

+----+-------------+-----------+------+---------------+-------------+---------+-------+-------+-------+
| id | select_type | table     | type | possible_keys | key         | key_len | ref   | rows  | Extra |
+----+-------------+-----------+------+---------------+-------------+---------+-------+-------+-------+
| 1  | SIMPLE      | example   | ref  | question_id   | question_id | 8       | const | 32096 |       |
+----+-------------+-----------+------+---------------+-------------+---------+-------+-------+-------+

然而,当我们执行相同的查询没有 EXPLAIN 时,只返回 18732 行

我们需要该表上的哪些索引来防止这种开销,但仍对两种查询都执行?


这是创建此表的代码:

创建表`示例`( `participant_id` BIGINT(20) UNSIGNED NOT NULL, `question_id` BIGINT(20) UNSIGNED NOT NULL, `given_answer_id` BIGINT(20) UNSIGNED NOT NULL, `status` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', 主键(`participant_id`、`question_id`、`given_answer_id`), 索引`question_id`(`question_id`) ) 引擎=InnoDB;

【问题讨论】:

  • 最好把这个问题移到dba.stackexchange.com
  • 32096 只是一个估计值。如果您有关于 question_id 的索引并且您的条件使用“=”,那么除非您使用“仅索引”,否则您不会做得更好:即将第二个索引创建为(question_id,participant_id,given_answer_id,status)。这样,DBMS 只需要读取索引,而永远不会去基表。但是,对于 3000 万行,您可能不需要大索引。

标签: mysql indexing query-optimization primary-key innodb


【解决方案1】:

我已按照建议将此问题发布到 dba.stackexchange.com,并收到了全面的答复:https://dba.stackexchange.com/questions/49275/mysql-looking-up-more-rows-than-needed-indexing-issue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2018-10-26
    • 2020-09-01
    • 2022-01-16
    • 2011-01-29
    相关资源
    最近更新 更多