我正在使用MU wordpress网站,我在查询中遇到问题需要花费太多时间才能执行。
SELECT wp_posts.* FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
WHERE 1=1 AND wp_posts.blog_id = '1'
AND wp_term_taxonomy.taxonomy = 'post_tag'
AND wp_terms.slug IN ('rate')
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 20
这个由wordpress执行的查询执行需要30-40秒,这太多了。
我已将列(已使用)编入索引。
答案 0 :(得分:0)
尝试并解释如下。
将以下内容粘贴到phpmyadmin并执行它: -
EXPLAIN SELECT wp_posts.* FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
WHERE 1=1 AND wp_posts.blog_id = '1'
AND wp_term_taxonomy.taxonomy = 'post_tag'
AND wp_terms.slug IN ('rate')
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 20
然后复制该结果并将其粘贴到原始问题中。它将详细说明在哪些表等中使用了哪些键
答案 1 :(得分:0)
将来,您可以随时重新编辑帖子并添加内容,例如转储EXPLAIN(sql语句),而不是转储到评论中。
查询本身看起来非常直接,并且每个解释的索引都显示正常,但对于WP_Posts表,我可能会根据
更改(或只添加另一个索引)( Blog_ID, Post_Type, Post_Status, ID, Post_Date )
这样,它首先匹配条件,然后匹配优化GROUP BY的ID,最后匹配Order By子句的Post_Date。
接下来,首先引擎不会尝试使用其他参考表,您是否尝试过添加关键字“STRAIGHT_JOIN”...
SELECT STRAIGHT_JOIN wp_posts.* ... rest of query
我要考虑的另一个替代方案是通过distinct预先查询ID,然后再联接回WP_Posts表...我不知道它是否会阻塞你做SELECT *并仅通过ID进行分组。
SELECT
wp_posts.*
FROM
( SELECT STRAIGHT_JOIN DISTINCT
WP.ID
from
wp_posts WP
INNER JOIN wp_term_relationships WPR
ON WP.ID = WPR.object_id
INNER JOIN wp_term_taxonomy WPTT
ON WPR.term_taxonomy_id = WPTT.term_taxonomy_id
INNER JOIN wp_terms WPT
ON WPTT.term_id = WPT.term_id
WHERE
1 = 1
AND WP.blog_id = '1'
AND WP.post_type = 'post'
AND WP.post_status = 'publish'
AND WPTT.taxonomy = 'post_tag'
AND WPT.slug IN ('rate')
GROUP BY
WP.ID
ORDER BY
WP.post_date DESC
LIMIT
0, 20 ) JustIDs
JOIN WP_Posts
on JustIDs.ID = WP_Posts.ID