多表连接和限制的最佳索引

时间:2014-01-23 17:59:06

标签: mysql indexing

我正在尝试创建索引来加速我的查询,但根据EXPLAIN代码,我在最后一个索引上不足。

SELECT *
FROM (
table_A AS tbA,
table_B AS tbB,
table_C AS tbC,
table_D AS tbD
)
WHERE tbB.id = tbA.id
AND tbD.x_id = tbA.x_id
AND tbD.u_id = tbC.u_id
AND tbB.type =0
ORDER BY tbA.updated DESC
LIMIT 25

查看EXPLAIN结果,table_B是唯一一个不使用索引的结果(并且它扫描的是40K行~5%的表), 根据'Extra'部分,“使用临时;使用filesort”

我在table_B(id,type)上创建了一个索引,但MySQL似乎没有使用它。

我缺少什么,如何完全优化我的查询?

由于

1 个答案:

答案 0 :(得分:0)

比较

#Using filesort
    EXPLAIN SELECT * FROM
    table_a AS tbA 
    INNER JOIN table_b AS tbB ON (tbA.id=tbB.id)
    INNER JOIN table_d AS tbD ON (tbD.x_id=tbA.x_id)
    INNER JOIN table_c AS tbC ON (tbD.u_id=tbC.u_id)
    WHERE tbB.`type` = 0
    ORDER BY tbA.updated DESC

with:

#Using temporary; Using filesort
    explain SELECT *
    FROM (
    table_a AS tbA,
    table_b AS tbB,
    table_c AS tbC,
    table_d AS tbD
    )
    WHERE tbB.id = tbA.id
    AND tbD.x_id = tbA.x_id
    AND tbD.u_id = tbC.u_id
    AND tbB.type =0
    ORDER BY tbA.updated DESC

使用SELECT * FROM t1,t2 WHERE t1.id = t2.id将导致使用临时。 此外,如果更新,x_id,u_id不是索引/初级,它将对选择产生不良影响,但您只需根据需要添加索引。确保知道this

你可以在这里玩我的例子: http://sqlfiddle.com/#!2/21d2da/3  (添加/删除查询的注释以查看差异)