重写MySQL查询以提高执行速度

时间:2015-10-28 作者:James Hayes

任何人都可以重新编写这个SQL查询以提高性能吗?

目前,在中执行此查询大约需要29秒BlueHost 服务器,而它需要6秒HostGator.com服务器。

我的目的是删除中存在的所有记录wp_postmeta 岗位类型表=\'attachment\' 并使用meta\\u key=_mycbgenie_managed_by \'

DELETE FROM wp_postmeta WHERE post_id IN 
( SELECT ID FROM wp_posts 
    WHERE post_type = \'attachment\' 
    AND post_parent IN 
        ( SELECT ID FROM 
            ( SELECT ID FROM wp_posts a 
                LEFT JOIN wp_postmeta b ON (a.ID = b.post_id) 
                LEFT JOIN wp_postmeta AS mt1 ON (a.ID = mt1.post_id) 
                WHERE post_type = \'product\' AND mt1.meta_key = \'_mycbgenie_managed_by\' 
             ) AS taskstodelete 
        ) 
) 

2 个回复
SO网友:RMS

尝试使用临时表将查询分割成更小的部分。拥有子查询总是耗费时间、内存和cpu。这应该可以奏效。

SO网友:luciole135

你做了两次相同的连接!一个就够了:

DELETE FROM wp_postmeta WHERE post_id IN 
( SELECT ID FROM wp_posts 
WHERE post_type = \'attachment\' 
AND post_parent IN 
    ( SELECT ID FROM 
        ( SELECT ID FROM wp_posts a 
            LEFT JOIN wp_postmeta AS mt1 ON (a.ID = mt1.post_id) 
            WHERE a.post_type = \'product\' AND mt1.meta_key = \'_mycbgenie_managed_by\' 
         ) AS taskstodelete 
    ) 
)