如何使用INNER JOIN和ORDER BY优化MySQL查询

时间:2012-11-27 10:30:32

标签: mysql sql

鉴于此查询:

EXPLAIN
SELECT mi.*, i1.sizes as tile_photo_sizes,
       i1.filename as tile_photo_filename,
       v.title_cached as venue_title,
       v.subtitle_cached as venue_subtitle,
       v.slug as venue_slug
FROM menuitems mi
INNER JOIN images i1 ON i1.id = mi.tile_photo_id
INNER JOIN menus m ON m.id = mi.menu_id
INNER JOIN venues v ON v.id = m.venue_id
WHERE NOT m.is_deleted AND v.slug="teplo" AND
      m.is_published AND v.is_published
ORDER BY mi.number ASC

我正在看到以下结果:

enter image description here

我尝试为joinwhereorder by中使用的每个列添加单独的索引,但它仍然使用临时文件。

我不想对其进行优化,但偶尔会导致错误,只能由托管服务提供商修复:Can't create/write to file '/mysql-temp/#sql_64e0_0.MYD' (Errcode: 17)

最大的表是menuitems(6,867),然后是图像(944),菜单(85),场地(79)。

UPD:删除ORDER BY不使用临时文件

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试更改查询以将主JOIN逻辑放入子查询中,并查看EXPLAIN是否执行得更好:

EXPLAIN
SELECT * FROM (
    SELECT mi.*, i1.sizes as tile_photo_sizes,
       i1.filename as tile_photo_filename,
       v.title_cached as venue_title,
       v.subtitle_cached as venue_subtitle,
       v.slug as venue_slug
    FROM menuitems mi
    INNER JOIN images i1 ON i1.id = mi.tile_photo_id
    INNER JOIN menus m ON m.id = mi.menu_id
    INNER JOIN venues v ON v.id = m.venue_id
    WHERE NOT m.is_deleted AND v.slug="teplo" AND
        m.is_published AND v.is_published
) as t
ORDER BY t.number ASC

这可能会导致另一种临时情况,但我对您的EXPLAIN结果感到好奇。