我的 Wordpress 博客中使用了以下查询,它获取用户发布的类别。当他在该类别中有帖子时,将显示该类别的名称。
这是一个非常非常慢的查询,因为它是一个大数据库,而且我与托管公司有问题。
我有 3 个类别,ID 3 称为新闻,4 称为文章,5 称为其他。我的代码是:
<?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>
谢谢大家!
最佳答案
从我周围的 wordpress 数据库的外观来看,我猜你在 WHERE
子句中为 wp_posts
使用的列没有索引> 表格。
尝试添加这样的索引:
ALTER TABLE wp_posts ADD INDEX (post_author,post_status)
。
我敢打赌你会看到速度的提高。
然而,最好的办法是在 SELECT
和 analyze the output 前面使用 EXPLAIN
手动运行该查询。 .
关于php - 非常非常慢的查询。我该如何改进它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723356/