Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL - basic 2 table query slow - where, index?
    primarykey
    data
    text
    <p>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:</p> <ol> <li>Does placement of join matter?</li> <li>Does order of where clause matter, or will MySQL optimize?</li> <li>Would and index help in my case?</li> </ol> <p>sql:</p> <pre><code>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'); </code></pre> <p>table/column info:</p> <pre><code>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 </code></pre> <ol> <li><p>Is there any advantage JOINing in the FROM, vs adding 'table1.CurrentName = table2.id' in the WHERE clause?</p></li> <li><p>There are 3 WHERE clauses (with the join). I ran EXPLAIN with various order combinations, and results seemed to be the same.</p></li> <li><p>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)</p></li> <li><p>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.</p></li> </ol> <p>explain results:</p> <pre><code>+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+ | 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) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload