basic 2 table query slow - where, index?
Posted by:
Matt S
Date: December 01, 2010 02:55PM
I have a MySQL 5.0 query regularly taking 14+ seconds, called from a web page, and users are impatient. It's fairly simple, selecting 11 columns from 2 tables. I have three questions:
1) Does placement of join matter?
2) Does order of where clause matter, or will MySQL optimize?
3) Would and index help in my case?
sql:
select table1.id, table1.DateOpened, table1.Status, table2.Name, etc
from (table1 join table2 on((table1.CurrentName = table2.id)))
where table1.Type = 'Add' and (Status = 'Open' OR Status = 'Pending');
table/column info:
- table1 has 750,000 rows, table2 1.5M rows.
- indexed: table1.id, table2.id
- INT columns: id, table1.CurrentName
- table1.Status = always populated with 1 of 4 values, maybe 300 are 'Open' or 'Pending'
- table1.Type = 3 possible values: 'Add', 'Change', or null
1) Is there any advantage JOINing in the FROM, vs adding 'table1.CurrentName = table2.id' in the WHERE clause?
2) There are 3 WHERE clauses (with the join). I ran EXPLAIN with various order combinations, and results seemed to be the same.
3a) I thought adding an index to table1.CurrentName may help, but now I'm thinking not. I modified the query to remove references to table2, and it still ran slow. (see 3b)
3b) Seems like the bulk of the slowdown may be just reading 800K records looking at the Type and Status values. Does it make sense to index these two columns, where there are only 3 or 4 possible values? I thought it only made sense when there were more unique values.
explain:
+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+
| 1 | SIMPLE | table1 | ALL | CurrentName | NULL | NULL | NULL | 733190 | Using where |
| 1 | SIMPLE | table2 | eq_ref | PRIMARY | PRIMARY | 4 | db.table1.CurrentName | 1 | |
+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+
2 rows in set (0.00 sec)