tags:

views:

51

answers:

2

I have 3 tables t1,t2,t3 each having 35K records.

select t1.col1,t2.col2,t3.col3
  from table1 t1,table2 t2,table3 t3
 where t1.col1 = t2.col1
   and t1.col1 = 100  
   and t3.col3 = t2.col3 
   and t3.col4 = 101 
   and t1.col2 = 102;

It takes more time to return the result (15 secs). I have proper indexes.

What is the optimal way of rewriting it?

+2  A: 

It's probably best to run your query with Explain Extended placed in front of it. That will give you a good idea of what indexes it is or isn't using. Include the output in your question if you need help parsing the results.

Kibbee
Thanks, when i ran explain statement with select i see 'Impossible WHERE noticed after reading const tables' as an extra message, do you have any idea on this?
Sharpeye500
It usually means that your where statement can never be true. Was this after you fixed the typo mentioned in the comments above? With impossible where, you shouldn't be getting any results back, and it should return very quickly.
Kibbee
Where statements are fine, just to indicate a sample query of the syntax of the query what i have, i did, while doing so i did a typo error which i have edited.
Sharpeye500
If you are getting "Impossible Where" you shouldn't be getting any results back, and it should return immediately. Remove the Explain Extended and see what results you get.
Kibbee
A: 

If you have an index based on t1.Col1 or t1.Col2, use THAT as the first part of your WHERE clause. Then, by using the "STRAIGHT_JOIN" clause, it tells MySQL to do exactly as I've listed here. Yes, this is older ANSI querying syntax which is still completely valid (as you originally had too), but should come out quickly with a response. The first two of the where clause will immediately restrict the dataset while the rest actually completes the joins to the other tables...

select STRAIGHT_JOIN
      t1.Col1,
      t2.Col2,
      t3.Col3
   from
      table1 t1,
      table2 t2,
      table3 t3
   where 
          t1.Col1 = 100
      and t1.Col2 = 102
      and t1.col1 = t2.col1
      and t2.col3 = t3.col3
      and t3.Col4 = 101
DRapp
Sharpeye500
Sometimes, SQL systems try to optimize based on a bunch of other elements they can determine from internal statistics. I was doing queries w/Government data of 15+ million records. Since it tried to use a lookup table as the basis of the query, it killed performance. When I redirected it to use MY PRIMARY table as basis, it flew through the data. You know best what your "primary" basis is, and what secondary / lookup tables are, so YOU can sometimes better judge which table SHOULD be used as the primary for processing.
DRapp
@Sharpeye, BTW, what was your performance result by the above query from the original 15 seconds...
DRapp