2014-10-02 73 views
0

我想避免在此查询的解释计划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 | 
+0

什么临时表? – Shaeldon 2014-10-02 12:12:31

+0

@Shaeldon:我认为他在解释结果的第一行中提到了“Using temporary”。 – 2014-10-02 12:13:52

+0

哪个是原始表格,哪个是临时的?!!!!!!!!!!!!!!!!! – nesreen 2014-10-02 12:16:29

回答

0

每时,有一个MySQL Documentation

Using temporary将出现ORDER BY子句和 不同的GROUP BY子句,或者如果ORDER BY或GROUP BY包含 表中的列o与加入队列中的第一个表相比,创建了一个 临时表。

在你发布查询,如果您删除order by共(OR)均group byorder by使用同一列p2m.merchant_id;它将不再使用内部临时表

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

+0

但这会按p2m.merchant_id命令,我需要按总数排序。 – Christoph 2014-10-02 12:48:24

+0

@Christoph,'按总数排序'或'按数量排序(merchent_id)'是'临时使用'的罪魁祸首。 – Rahul 2014-10-02 12:50:27