Reputation: 416
I have 3 tables (not writing all and actual field names)
Contract (~30 000 rows)
|id|client_id|contract_nr|....
Container (~30 000 rows
|id|contract_nr|phone_1(varchar)|....
Client (~35 000 rows)
|id|phone_2(varchar)|phone_3(varchar)|phone_4(varchar)|....
I need to search for phone numbers so i try this - if i serch for one phone number for example in container.phone_1
SELECT *
FROM contract JOIN client
ON contract.client_id = client.id
JOIN container
ON contract.contract_nr = container.contract_nr
WHERE container.phone_1 LIKE '264%'
id select_type table type possible_keys key key_len ref rows filtered Extra
-------------------------------------------------------------------------------------------------------------
1 SIMPLE container range contract_nr,phone_1 phone_1 63 NULL 912 100.00 Using where
1 SIMPLE contract ref contract_nr,client_id contract_nr 26 container.contract_nr 1 100.00
1 SIMPLE client eq_ref PRIMARY,id PRIMARY 3 contract.client_id 1 100.00
but when i start to add phone numbers from client using OR
SELECT *
FROM contract JOIN client
ON contract.client_id = client.id
JOIN container ON contract.contract_nr = container.contract_nr
WHERE (
container.phone_1 LIKE '264%' OR
client.phone_2 LIKE '264%' OR
client_phone_3 LIKE '264%'
)
EXPLAIN EXTENDED:
id select_type table type possible_keys key key_len ref rows filtered Extra
-------------------------------------------------------------------------------------------------------------
1 SIMPLE container ALL k_ligums,k_telef NULL NULL NULL 32113 100.00
1 SIMPLE contract ref contract_nr,client_id contract_nr 26 za.zaao_konteineri.k_ligums 1 100.00
1 SIMPLE client eq_ref PRIMARY,id PRIMARY 3 contract.client_id 1 100.00 Using where
I have indexed all the fields that are used to join tables and that are used to search for. I also tried to create multiple-column index for client and container tables having all the search rows included - no difference.
How can i avoid scanning of 32113 rows for container table?
Upvotes: 0
Views: 90
Reputation: 249
use and instead of where.
SELECT * FROM contract JOIN client ON contract.client_id = client.id JOIN container ON contract.contract_nr = container.contract_nr AND (container.phone_1 LIKE '264%' client.phone_2 LIKE '264%' OR client_phone_3 LIKE '264%')
Upvotes: -1