在解释计划中避免临时表

时间:2014-10-02 12:07:57

标签: mysql

我想避免此查询的解释计划中的temporary table

http://sqlfiddle.com/#!2/544dd/1

EXPLAIN SELECT count( p2m.product_id ) AS total, p2m.merchant_id
FROM merchants_to_products p2m
LEFT JOIN products p ON p2m.id = p2m.product_id
GROUP BY p2m.merchant_id
ORDER BY total DESC

| ID | SELECT_TYPE | TABLE |  TYPE | POSSIBLE_KEYS |        KEY | KEY_LEN |    REF | ROWS |                                        EXTRA |
|----|-------------|-------|-------|---------------|------------|---------|--------|------|----------------------------------------------|
|  1 |      SIMPLE |   p2m | index |        (null) | product_id |       8 | (null) |   11 | Using index; Using temporary; Using filesort |
|  1 |      SIMPLE |     p | index |        (null) |    PRIMARY |       4 | (null) |   10 |                                  Using index |

1 个答案:

答案 0 :(得分:0)

MySQL Documentation

  当存在ORDER BY子句和a时,将出现

Using temporary   不同的GROUP BY子句,或者如果包含ORDER BY或GROUP BY   来自连接队列中第一个表以外的表的列,a   临时表已创建。

在您发布的查询中,如果您完全删除order by(OR),请在p2m.merchant_idgroup by中使用同一列order by;它将不再使用内部临时表

EXPLAIN SELECT count( p2m.product_id ) AS total, 
p2m.merchant_id
FROM merchants_to_products p2m
LEFT JOIN products p ON p2m.id = p.id
GROUP BY p2m.merchant_id
ORDER BY p2m.merchant_id DESC

查看修改后的Fiddle