1

My query seems to be very similar to example from http://dev.mysql.md/doc/refman/5.1/en/in-subquery-optimization.html, but unfortunately receipts from this manual don't work for me.

When I run them separately, both inner and outer queries use indexes, but when I run the whole query, outer query scans the whole table...

mysql> explain select smsId FROM SMSDelivery WHERE smsId IN (SELECT smsId FROM SMS WHERE phoneNumber='123456' OR fromUser='5678p' OR toUser='5124p') \G

  *************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
  table: SMSDelivery
  type: index
  possible_keys: NULL
  key: FK75C784D70BE5EC9
  key_len: 4
  ref: NULL
  rows: 1337017
  Extra: Using where; Using index

*************************** 2. row ***************************
     id: 2
    select_type: DEPENDENT SUBQUERY
    table: SMS
     type: unique_subquery
    possible_keys: PRIMARY,phoneNumber,fromUser,toUser
    key: PRIMARY
     key_len: 4
     ref: func
     rows: 1
     Extra: Using where
    2 rows in set (0.00 sec)

1 Answer 1

1

can you try this:

EXPLAIN
SELECT
 sd.* 
FROM 
 SMSDelivery sd
INNER JOIN
(
 SELECT smsId FROM SMS WHERE phoneNumber='123456' OR fromUser='5678p' OR toUser='5124p'
) s ON sd.smsId = s.smsId;
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much - inner join uses indexes, not table scan!
You could also use an 'EXISTS' instead of an 'IN'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.