How do I tell the MySQL Optimizer to use the index on a derived table?

前端 未结 3 1350
我在风中等你
我在风中等你 2021-02-04 19:28

Suppose you have a query like this...

SELECT T.TaskID, T.TaskName, TAU.AssignedUsers
FROM `tasks` T
    LEFT OUTER JOIN (
        SELECT TaskID, GROUP_CONCAT(U.F         


        
3条回答
  •  遇见更好的自我
    2021-02-04 20:08

    There is a solution to this in MySQL Server 5.6 - the preview release (at the time of this writing).

    http://dev.mysql.com/doc/refman/5.6/en/from-clause-subquery-optimization.html

    Although, I'm not sure if the MySQL Optimizer will re-use indexes that already exist when it "adds indexes to the derived table"

    Consider the following query:

    SELECT * FROM t1 JOIN (SELECT * FROM t2) AS derived_t2 ON t1.f1=derived_t2.f1;

    The documentation says: "The optimizer constructs an index over column f1 from derived_t2 if doing so would permit the use of ref access for the lowest cost execution plan."

    OK, that's great, but does the optimizer re-use indexes from t2? In other words, what if an index existed for t2.f1? Does this index get re-used, or does the optimizer recreate this index for the derived table? Who knows?

    EDIT: The best solution until MySQL 5.6 is to create a temporary table, create an index on that table, and then run the SELECT query on the temp table.

提交回复
热议问题