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 |
+----+-------------+-------------------+------+-----------------------------------------+---------------------------+---------+---------------------------------------+---开发者_Python百科---+-----------------+
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.
try create an index on tableA with the following column (column_a)
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
精彩评论