简体   繁体   中英

mysql select with join very slow

I have two tables A and B. A has about 29 million rows and B is a temporary table with about 1000 rows.

The query is as below -

select DISTINCT Table_A.column_a from Table_B join Table_A on Table_B.ID_b = Table_A.ID_a;

I have a composite index key2 on (ID_a, column_a)

The query takes about 20 secs to run.

The explain is as below -

------------+
| id | select_type | table             | type | possible_keys                           | key                       | key_len | ref                                   | rows | Extra           |
+----+-------------+-------------------+------+-----------------------------------------+---------------------------+---------+---------------------------------------+------+-----------------+
|  1 | SIMPLE      | Table_B           | ALL  | NULL                                    | NULL                      | NULL    | NULL                                  | 1507 | Using temporary |
|  1 | SIMPLE      | Table_A           | ref  | key1 ,key2                              | key2                      | 3       | DB_name.Table_B.ID_b                  |  963 | Using index     |
+----+-------------+-------------------+------+-----------------------------------------+---------------------------+---------+---------------------------------------+------+-----------------+

How can I optimize this query?

Thanks

desc Table_A 
| id       | bigint(8) unsigned    | NO | PRI | NULL | auto_increment |
| column_a | mediumint(8) unsigned | NO | MUL |      |                | 
| column_1 | mediumint(8) unsigned | NO | MUL |      |                |
| id_a     | mediumint(8) unsigned | NO | MUL |      | 
| column_2 | smallint(5) unsigned  | NO | MUL | NULL |                | 
| column_3 | smallint(5) unsigned  | NO |     | NULL |                | 
| column_4 | smallint(5) unsigned  | NO | MUL | NULL |                | 
| column_5 | smallint(5) unsigned  | NO |     | NULL |                |

Create an index on the temporary table B, column ID_b, you should'nt get anymore the 'Using temporary in the "Extra" column after that and it should be better. Use a CREATE INDEX statement.

尝试使用以下列(column_a)在tableA上创建索引

Add proper indexes on a colums. Explain should help there and it should speed up your query a lot.

do not change any index

EDIT i miss the index's order, change the key2 to (column_a, id_a)

Try:

select DISTINCT Table_A.column_a 
from Table_A straight_join 
Table_B on Table_B.ID_b = Table_A.ID_a;

pls show the explain result ,tkx

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