非常非常慢的查询。我该如何改进它?
以下查询在我的WordPress的博客使用,它得到用户已张贴在类别。当他在类别后,显示该类别的名称。非常非常慢的查询。我该如何改进它?
这是一个非常非常慢的查询,因为它是一个大的数据库,我有一个托管公司的问题。
我有3类,用所谓的新闻编号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
手动运行该查询。
有你posts.ID
,relationships.object_ID
,relationships.term_taxonomy_id
,tax.term_taxonomy_id
,tax.term_id
,terms.term_id
,posts.post_status
,posts.post_author
和tax.taxonomy
指标?
你好,我是新来的..我怎么知道这个指数会做什么? – EnexoOnoma 2011-04-19 22:29:14
在每个使用的表上进行['DESCRIBE'](http://dev.mysql.com/doc/refman/5.0/en/describe.html)查询并搜索“KEY”行。索引使您可以更快地进行“SELECT”查询。更多关于[mysql文档索引](http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html) – Bil 2011-04-19 22:30:48
INDEX会做什么? – EnexoOnoma 2011-04-19 22:28:47
索引是数据库的基本功能。有很多需要了解的内容,超过Stack Overflow帖子中的内容,但是本质上它们加快了SELECT查询的速度。缺点是它们减慢了INSERT/UPDATE查询,并且*可能会占用大量的磁盘空间。 MySQL手册是一个很好的开始阅读它们的地方:http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html – zombat 2011-04-19 22:32:13
我已经运行了查询并且它说它已被正确执行。所以我猜他们没有索引? – EnexoOnoma 2011-04-19 22:51:30