When joining to a very small/empty table why MySQL makes a full scan in spite of I'm using “LIMIT”?

后端 未结 3 1329
栀梦
栀梦 2021-01-16 15:54

EDIT: I removed the GROUP BY clause from the example queries but the same problem shows \"When I join table x to an empty/1 row table y MySQL makes a full table

3条回答
  •  终归单人心
    2021-01-16 16:13

    The MySQL optimizer will decide on join order/method first, and then check whether, for the chosen join order, it is possible to avoid sorting by using an index. For the slow query in this question, the optimizer has decided to use Block-Nested-Loop (BNL) join.

    BNL is usually quicker than using an index when one of the tables is very small (and there is no LIMIT).

    However, with BNL, rows will not necessarily come in the order given by the first table. Hence, the result of the join needs to be sorted before applying the LIMIT.

    You can turn off BNL by set optimizer_switch = 'block_nested_loop=off';

提交回复
热议问题