查询非常慢。我怎样才能改进它?

时间:2011-04-19 22:12:33

标签: php mysql wordpress

我的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>

谢谢大家!

2 个答案:

答案 0 :(得分:3)

根据我所说的wordpress数据库的外观来判断,我猜你在WHERE子句的wp_posts子句中使用的列上没有索引。

尝试添加这样的索引:

ALTER TABLE wp_posts ADD INDEX (post_author,post_status)

我打赌你看到了加速。

但最好的办法是在EXPLAINanalyze the output前面SELECT手动运行该查询。

答案 1 :(得分:0)

您是否对posts.IDrelationships.object_IDrelationships.term_taxonomy_idtax.term_taxonomy_idtax.term_idterms.term_idposts.post_status,{进行了索引{1}}和posts.post_author