IF condition on temporary table takes long time for query execution
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, needs INDEX(col1, col2).

Break the query up into two in order to avoid the IF clauses.  Something like

SELECT ... JOIN ...
UNION
SELECT ... LEFT JOIN WHERE temp.col1 IS NULL AND ...


That will need parens around it before doing the outer GROUP BY.