SELECT actualTable.column1, actualTable.column2, actualTable.column3
FROM table1 actualTable LEFT JOIN (
SELECT column1, column2
FROM table2
GROUP BY column1
ORDERBY ASC
) temp
WHERE IF(temp.column1 IS NOT NULL, temp.column1, actualTable.column1)
AND IF(temp.column2 IS NOT NULL, temp.column2, actualTable.column2)
GROUP BY actualTable.column1;
Above query is for reference. I have used 6 tables and added necessary joins.
The problem is that IF condition on Temporary table in Where cluase takes time. If i remove it then it takes less time to execute.
Best Answer
It is improper to "group by col1" but fetch col2 unless they col2 is either directly derivable from col1 or is an "aggregate".
The
ORDER BY
in the derived table will be ignored (once the two syntax errors are fixed). Why do you have it?table2
, as the query stands, needsINDEX(col1, col2)
.Break the query up into two in order to avoid the
IF
clauses. Something likeThat will need parens around it before doing the outer
GROUP BY
.