Search code examples
mysqldatabaseinner-join

Difference between "INNER JOIN table" and "INNER JOIN (SELECT table)"?


I work on a query in mysql that spend 30 sec to execute. The format is like this :

SELECT id
FROM table1 t1
INNER JOIN table2 t2
ON t1.id = t2.idt2

The INNER JOIN take 25 of 30 sec. When I write this like this :

SELECT id
FROM table1 t1
INNER JOIN (
    SELECT idt2,col1,col2,col3
    FROM table2
) t2
ON t1.id = t2.idt2

It take only 8 sec! Why does it work? I'm afraid of losing data.

(obviously, my query is more complex than this one, it's just an exemple)


Solution

  • Well you haven't shown us the EXPLAIN output

    EXPLAIN SELECT id
    FROM table1 t1
    INNER JOIN table2 t2
    ON t1.id = t2.idt2
    

    this would definitly give us some insights of your query and table sctructures.

    Based on your scenario, 1st query seems like you have issues with indexing.

    What happened in your 2nd query is the optimizer is creating a temporary set from your subquery furthering filtering your data. I dont recommend doing that in MOST cases. Purpose of subquery is to solve complex logic, not an instant solution for everything.