我的Wordpress博客中使用了以下查询,它获取了用户发布的类别。当他在该类别中有帖子时,会显示该类别的名称。
这是一个非常非常慢的查询,因为它是一个大型数据库,我与托管公司有问题。
我有3个类别,id 3称为News,4个称为Articles,5个称为Others。我的代码是:
<?php
$author = get_query_var('author');
$categories = $wpdb->get_results("
SELECT DISTINCT(terms.term_id) as ID, terms.name, terms.slug, tax.description
FROM $wpdb->posts as posts
LEFT JOIN $wpdb->term_relationships as relationships ON posts.ID = relationships.object_ID
LEFT JOIN $wpdb->term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN $wpdb->terms as terms ON tax.term_id = terms.term_id
WHERE 1=1 AND (
posts.post_status = 'publish' AND
posts.post_author = '{$post->post_author}' AND
tax.taxonomy = 'category' )
ORDER BY terms.term_id ASC
");
?>
<ul>
<?php foreach($categories as $category) : ?>
<?php if ( ($category->ID == '3') || ($category->ID == '4') || ($category->ID == '5')) { ?>
<li>
<a href="<?php echo get_category_link( $category->ID ); ?>/?author_name=<?php echo $curuser->user_login; ?>" title="<?php echo $category->name ?>">
<?php echo $category->name; ?>
</a>
</li>
<?php } ?>
<?php endforeach; ?>
</ul>
谢谢大家!
答案 0 :(得分:3)
根据我所说的wordpress数据库的外观来判断,我猜你在WHERE
子句的wp_posts
子句中使用的列上没有索引。
尝试添加这样的索引:
ALTER TABLE wp_posts ADD INDEX (post_author,post_status)
。
我打赌你看到了加速。
但最好的办法是在EXPLAIN
和analyze the output前面SELECT
手动运行该查询。
答案 1 :(得分:0)
您是否对posts.ID
,relationships.object_ID
,relationships.term_taxonomy_id
,tax.term_taxonomy_id
,tax.term_id
,terms.term_id
,posts.post_status
,{进行了索引{1}}和posts.post_author
?