I have following query
SELECT o.order_id,
p.pre_sale_phone_manual_id AS id,
p.created,
p.user_id
FROM `order` o
LEFT JOIN `customer` c ON c.customer_id = o.customer_id,
`pre_sale_phone_manual` p
LEFT JOIN `pre_sale_phone_manual` p1 ON p.pre_sale_phone_manual_id=p1.pre_sale_phone_manual_id
AND p.created > p1.created
WHERE p1.user_id IS NULL
AND p.phone <> ""
AND REPLACE(REPLACE(REPLACE(REPLACE(c.phone, "-", ""), ".", ""), "+", ""), " ", "") LIKE CONCAT('%', RIGHT(REPLACE(REPLACE(REPLACE(REPLACE(p.phone, "-", ""), ".", ""), "+", ""), " ", ""), 10))
AND o.created > p.created
AND o.created < (DATE_ADD(p.created, INTERVAL 183 DAY))
AND o.created > '2013-12-30 08:28:37'
The query basically does is matching the phone numbers of customer's and entry in pre_sale_phone_manual tables. The pre_sale_phone_manual's record should be before order's date and should be within 6 months (183 days) and should match with the pre_sale_phone_manual table's first entry because there can be duplicate entries by other users.
As I've found the slowness is in the join between order table and pre_sale_phone_manual table due to there is no 1 to 1 join and scans the whole tables and obviously for INTERVAL 183 DAY
Following is the EXPLAIN for query
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: o
type: ALL
possible_keys: order_created_index,fk_order_customer
key: NULL
key_len: NULL
ref: NULL
rows: 110658
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: p
type: ALL
possible_keys: created,phone
key: NULL
key_len: NULL
ref: NULL
rows: 2053
Extra: Using where; Using join buffer
*************************** 3. row ***************************
id: 1
select_type: SIMPLE
table: p1
type: eq_ref
possible_keys: PRIMARY,created
key: PRIMARY
key_len: 4
ref: 463832_yii_adm_t4f.p.pre_sale_phone_manual_id
rows: 1
Extra: Using where; Not exists
*************************** 4. row ***************************
id: 1
select_type: SIMPLE
table: c
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: 463832_yii_adm_t4f.o.customer_id
rows: 1
Extra: Using where
Following stats are from mysql slow query log
Query_time: 126.038395 Lock_time: 0.000303 Rows_sent: 72 Rows_examined: 15266616
Following fields are indexed already,
order.created
pre_sale_phone_manual.created
pre_sale_phone_manual.phone
and PKs and FKs with _id suffix
Please help for optimizing the query and thanks for your time.