I have the following query selecting everything from the notes
table where the input(ex: bob) is not in the orders
table.
SELECT * FROM `notes` WHERE notes.customer_email NOT IN
(SELECT customers_email_address FROM orders)
AND ((customer_phone LIKE '%bob%')
OR (customer_name LIKE '%bob%')
OR (customer_email LIKE '%bob%'))
AND customers_id IS NULL
GROUP BY `customer_email`
ORDER BY `customer_name`
DESC LIMIT 50
This fat boy of a query is taking ~80 seconds on my dev machine and ~7 seconds on the live server.
Two questions:
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `notes` ADD INDEX `notes_idx_customers_id_customer_email` (`customers_id`,`customer_email`);
ALTER TABLE `orders` ADD INDEX `orders_idx_customers_address` (`customers_email_address`);
SELECT
*
FROM
`notes`
WHERE
NOT EXISTS (
SELECT
1
FROM
orders
WHERE
(
notes.customer_email = orders.customers_email_address
)
)
AND (
(
`notes`.customer_phone LIKE '%bob%'
)
OR (
`notes`.customer_name LIKE '%bob%'
)
OR (
notes.customer_email LIKE '%bob%'
)
)
AND `notes`.customers_id IS NULL
GROUP BY
notes.`customer_email`
ORDER BY
`notes`.`customer_name` DESC LIMIT 50