简体   繁体   中英

Why does MySQL pick the wrong index in JOIN query?

I use a simple JOIN query, however MySQL keep showing wrong index in the EXPLAIN plan.

It select an index on a column that does not participate in the query.

The query is based on the primary key. I tried removing the index but then the optimizer picks another irrelevant index.

In my case table a holds ~2.5 million records and table b ~5 million records. Each record in a has ~2 records in b.

I'm using MySql 5.6.

I did ANALYZE and CHECK on the tables.

The query takes about 70 seconds, it uses the wrong index and performs a nested loop, why?

SELECT 
IFNULL(SUM(a.val),0) as total
FROM a , b
where a.id = b.a_id;

1   SIMPLE  a   index   PRIMARY idx_a_c_id  5       2406691 Using index
1   SIMPLE  tv  ref idx_a_id idx_a_id   4   capb_1.a.id 1

# id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'SIMPLE', 'spd_transaction', 'index', 'PRIMARY', 'idx_a_c_id', '5', NULL, '2406691', 'Using index'
'1', 'SIMPLE', 'tv', 'ref', 'idx_a_id', 'idx_a_id', '4', 'a.id', '1', NULL

1) Looking at the nature of SQL (no predicates), i would suggest using hint (which i don't encourage often) to ignore index(s) and force DB engine to use FTS (Full Table Scan).

FTS will be better than using any index in this scenario.

SELECT 
IFNULL(SUM(a.val),0) as total
FROM a , b USE INDEX /* Specify no index here to ignore index and force FTS*/
where a.id = b.a_id;

I did not recommend to drop indexes on tables as am not aware of their in use elsewhere in ur application.

2) I would also suggest to remove JOIN on table 'B' as SQL is not making use of this costly JOIN of large table in output.

SELECT 
IFNULL(SUM(a.val),0) as total
FROM a USE INDEX /* Specify no index here to ignore index and force FTS*/
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM