如何让这个MySql WordPress查询运行得更快?

时间:2016-02-20 12:02:15

标签: mysql wordpress optimization entity-attribute-value

我在WordPress中运行针对某些非常大的表的以下查询。有没有办法重新组织它以便运行得更快?目前它花了8秒钟,这对我的用例来说太慢了,我需要称它为600K次。位wp_term_taxonomy.term_id = 18将是动态的,如:wp_term_taxonomy.term_id = category_id

SELECT  `ID` AS athlete_id, `post_title` AS athlete_name, `post_name` AS athlete_slug,
        body_weight.weight, performance.speed
    FROM  `wp_posts`
    INNER JOIN  
      ( SELECT  `post_id`, `meta_value` AS weight
            FROM  `wp_postmeta`
            WHERE  (`meta_key` = 'athlete_weight')
      ) body_weight ON wp_posts.ID = body_weight.post_id
    INNER JOIN  
      ( SELECT  `post_id`, `meta_value` AS speed
            FROM  `wp_postmeta`
            WHERE  (`meta_key` = 'athlete_speed')
      ) performance ON wp_posts.ID = performance.post_id
    LEFT JOIN  wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
    LEFT JOIN  wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id =
                                         wp_term_taxonomy.term_taxonomy_id)
    LEFT JOIN  wp_terms ON (wp_terms.term_id = wp_term_taxonomy.term_id)
    WHERE  wp_posts.post_status = 'publish'
      AND  wp_posts.post_type = 'athlete'
      AND  ((wp_term_taxonomy.taxonomy = 'athletics_category'
                      AND  wp_term_taxonomy.term_id = 18)
              OR  (wp_terms.term_id is null)
           );

1 个答案:

答案 0 :(得分:0)

由于tmp表中缺少索引,因此使用多个JOIN子查询效率特别低。 (是的,5.6动态添加了一个索引,但效率仍然较低。)

相反,JOIN到表,而不是子查询:

SELECT ...
    ms.meta_value AS speed
    ...
FROM ...
JOIN wp_postmeta AS ms
    ON ms.post_id = wp_posts.ID

(与另一个相同,但使用不同的别名)

(这是为什么EAV模式很痛苦的一个例子。)