JOIN with subquery ("Derived" table)

Download mysql eBook


SELECT x, ...
    FROM ( SELECT y, ... FROM ... ) AS a
    JOIN tbl  ON tbl.x = a.y
    WHERE ...

This will evaluate the subquery into a temp table, then JOIN that to tbl.

Prior to 5.6, there could not be an index on the temp table. So, this was potentially very inefficient:

    FROM ( SELECT y, ... FROM ... ) AS a
    JOIN ( SELECT x, ... FROM ... ) AS b  ON b.x = a.y
    WHERE ...

With 5.6, the optimizer figures out the best index and creates it on the fly. (This has some overhead, so it is still not 'perfect'.)

Another common paradigm is to have a subquery to initialize something:

        @n := @n + 1,
    FROM ( SELECT @n := 0 ) AS initialize
    JOIN the_real_table
    ORDER BY ...

(Note: this is technically a CROSS JOIN (Cartesian product), as indicated by the lack of ON. However it is efficient because the subquery returns only one row that has to be matched to the n rows in the_real_table.)


Contributors: 2
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook