我怎样才能使这个 MySql WordPress 查询更快地达到 运行?
How can I get this MySql WordPress query to run faster?
我在 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)
);
使用多个 JOIN
子查询效率特别低,因为 tmp table 中缺少索引。 (是的,5.6 会即时添加索引,但这仍然效率较低。)
相反,加入 table,而不是子查询:
SELECT ...
ms.meta_value AS speed
...
FROM ...
JOIN wp_postmeta AS ms
ON ms.post_id = wp_posts.ID
(另一个同上,但使用不同的别名)
(这是为什么 EAV 模式很痛苦的一个例子。)
我在 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)
);
使用多个 JOIN
子查询效率特别低,因为 tmp table 中缺少索引。 (是的,5.6 会即时添加索引,但这仍然效率较低。)
相反,加入 table,而不是子查询:
SELECT ...
ms.meta_value AS speed
...
FROM ...
JOIN wp_postmeta AS ms
ON ms.post_id = wp_posts.ID
(另一个同上,但使用不同的别名)
(这是为什么 EAV 模式很痛苦的一个例子。)