AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 149810
Accepted
Noah Goodrich
Noah Goodrich
Asked: 2016-09-16 08:37:37 +0800 CST2016-09-16 08:37:37 +0800 CST 2016-09-16 08:37:37 +0800 CST

MySQL Query Optimizer Ingoring Index no Timestamp

  • 772

Eu tenho a seguinte tabela:

CREATE TABLE `matches` (
  `id` char(32) NOT NULL,
  `borrower_id` int(10) unsigned NOT NULL,
  `product_id` int(10) unsigned NOT NULL,
  `category_id` int(10) unsigned NOT NULL,
  `lender_id` int(10) unsigned NOT NULL,
  `classification_id` int(10) unsigned DEFAULT NULL,
  `status` enum('accepted','partial','potential','rejected') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `classification` varchar(255) DEFAULT NULL,
  `category` varchar(255) DEFAULT NULL,
  `lender` varchar(255) DEFAULT NULL,
  `product` varchar(255) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `borrower_id` (`borrower_id`,`product_id`),
  KEY `status` (`status`),
  KEY `created_timestamp` (`created`),
  KEY `borrower_id_2` (`borrower_id`,`product_id`,`created`),
  KEY `borrower-product-classification` (`borrower_id`,`product_id`,`classification_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Quando executo EXPLAIN SELECT COUNT(*) FROM bi.matches WHERE created >= '2016-09-10';, obtenho os seguintes resultados:

| id | select_type | table  | type  |   possible_keys   |        key  | key_len | ref  |   rows   |          Extra                            |

|----|-------------|--------|------|-------|-------------------|------------------|---------|------|----------|--------------------------|      

    1| SIMPLE      | matches | range | created_timestamp | created_timestamp |       4 | NULL | 13288480 | Using where; Using index |

Mas quando eu executo esta consulta:

EXPLAIN SELECT COUNT(*)
FROM bi.matches m
INNER JOIN bi.matches m1
    ON m.borrower_id = m1.borrower_id
    AND m.product_id = m1.product_id
    AND m.created > m1.created
LEFT OUTER JOIN bi.matches m2
    ON m1.borrower_id = m2.borrower_id
    AND m1.product_id = m2.product_id
    AND m.created > m2.created
    AND (m1.created < m2.created OR (m1.created = m2.created AND m1.id < m2.id))
WHERE m.created >= '2016-09-10'
AND m2.id IS NULL
AND m.status = m1.status;

Eu recebo a seguinte explicação:

| id | select_type | table | type |                                    possible_keys                                    |               key               | key_len |               ref                |   rows   |                Extra                 |

|==========================================================================|
|  1 | SIMPLE      | m     | ALL  | borrower_id,status,created_timestamp,borrower_id_2,borrower-product-classification  | NULL                            | NULL    | NULL                             | 75151052 | Using where |

|  1 | SIMPLE      | m1    | ref  | borrower_id,status,created_timestamp,borrower_id_2,borrower-product-classification  | borrower-product-classification | 8       | bi.m.borrower_id,bi.m.product_id |        3 | Using where                          |

|  1 | SIMPLE      | m2    | ref  | PRIMARY,borrower_id,created_timestamp,borrower_id_2,borrower-product-classification | borrower_id_2                   | 8       | bi.m.borrower_id,bi.m.product_id |        4 | Using where; Not exists; Using index |

Por que o MySQL usaria created_timestampna consulta mais básica, mas não quando as junções estão envolvidas?

Também aqui está a saída deSHOW INDEXES FROM bi.matches

|  Table  | Non_unique |            Key_name             | Seq_in_index |    Column_name    | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
|=========================================================================|
| matches |          0 | PRIMARY                         |            1 | id                | A         |    75151052 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower_id                     |            1 | borrower_id       | A         |      434399 | NULL     | NULL   |      | BTREE      |         |               |
| matches |          1 | borrower_id                     |            2 | product_id        | A         |    18787763 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | status                          |            1 | status            | A         |        2232 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | created_timestamp               |            1 | created           | A         |       37075 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower_id_2                   |            1 | borrower_id       | A         |      521882 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower_id_2                   |            2 | product_id        | A         |    18787763 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower_id_2                   |            3 | created           | A         |    75151052 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower-product-classification |            1 | borrower_id       | A         |      478669 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower-product-classification |            2 | product_id        | A         |    25050350 | NULL     | NULL   |      | BTREE      |         |               |

| matches |          1 | borrower-product-classification |            3 | classification_id | A         |    18787763 | NULL     | NULL   | YES  | BTREE      |         |               |
mysql performance
  • 2 2 respostas
  • 247 Views

2 respostas

  • Voted
  1. Best Answer
    Jehad Keriaki
    2016-09-16T16:22:17+08:002016-09-16T16:22:17+08:00

    Então, aqui está a conclusão dos comentários:

    Executando isso: EXPLAIN SELECT * FROM bi.matches WHERE created >= '2016-09-10';mostrou que o índice não está sendo usado, enquanto na select count(*)...consulta original o índice foi usado. A razão é que basta contar os valores não nulos do campo criado.

    É mais provável que a maioria das linhas satisfaça a wherecondição em data, então o otimizador decide que não vale a pena usar o índice. Em vez disso, execute uma verificação completa.

    Para que o índice seja usado, um intervalo de datas menor ajudaria. isto é WHERE created BETWEEN '2016-09-10' AND '2016-09-11'. Use intervalos ainda menores se o índice não tiver sido usado.

    • 1
  2. Rick James
    2016-09-17T09:58:19+08:002016-09-17T09:58:19+08:00

    Como sua pergunta 'real' é sobre desempenho, ignorarei a pergunta "não usarei esse índice" e ..

    KEY `status` (`status`),  -- Drop (index on a flag is usually ignored)
    KEY `borrower_id` (`borrower_id`,`product_id`),  -- Redundant, drop it.
    KEY `borrower_id_2` (`borrower_id`,`product_id`,`created`),  -- good for LEFT JOIN; keep
    KEY  (`borrower_id`,`product_id`, status, `created`),  -- good for 1st JOIN; add
    
    • 0

relate perguntas

  • Onde posso encontrar o log lento do mysql?

  • Como posso otimizar um mysqldump de um banco de dados grande?

  • Quando é o momento certo para usar o MariaDB em vez do MySQL e por quê?

  • Como um grupo pode rastrear alterações no esquema do banco de dados?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve