I have a nested MySQL query having relation in tables with over 500000 records in each. The query takes 60 seconds to fetch results and Indexing has been done in all tables.
Please suggest to reduce its execution time. Thanks in advance.
SELECT t1.col1,t1.col2
FROM table1 AS t1
WHERE t1.col2 IN
(
SELECT DISTINCT(t2.col1) FROM table2 AS t2 WHERE t2.col2 IN
(
SELECT t3.col1
FROM table3 AS t3
WHERE t3.col2 = '04' ORDER BY t3.col1 ASC
)
ORDER BY t2.col1 ASC
)
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `table1` ADD INDEX `table1_idx_col2` (`col2`);
ALTER TABLE `table2` ADD INDEX `table2_idx_col1` (`col1`);
ALTER TABLE `table3` ADD INDEX `table3_idx_col2_col1` (`col2`,`col1`);
SELECT
t1.col1,
t1.col2
FROM
table1 AS t1
WHERE
t1.col2 IN (
SELECT
DISTINCT (t2.col1)
FROM
table2 AS t2
WHERE
EXISTS (
SELECT
1
FROM
table3 AS t3
WHERE
(
t3.col2 = '04'
)
AND (
t2.col2 = t3.col1
)
ORDER BY
t3.col1 ASC
)
ORDER BY
t2.col1 ASC)