如何提高复杂的wp_查询的速度?

时间:2016-09-17 作者:gordie

我做了a Wordpress plugin that checks if a bbPress forum / topic has been read.

基本上,当阅读主题时,会向主题添加一个post-meta-bbppu-read-by,它的值为用户ID。

然后,如果我想获取阅读主题(例如,这里,对于论坛ID 3526和用户#1);我对这些参数使用自定义查询:

$read_query_args = array(
    \'post_type\'                 => \'topic\',
    \'post_parent\'               => 3526,
    \'posts_per_page\'            => -1,
    \'post_status\'               => \'publish,closed,private\',
    \'meta_query\' => array(
        //fetch only read posts
        array(
            \'key\'       => \'bbppu_read_by\',
            \'value\'     => 1, //user ID
            \'compare\'   => \'=\',
        ),
        //ignore posts that are older than the user\'s registration time
        array(
            \'key\' => \'_bbp_last_active_time\',
            \'value\' => \'2015-10-04 11:51:05\',
            \'compare\' => \'>\',
        ),

    ),
    //try to optimize the query
    \'fields\'                    => \'ids\', //get only IDs
    \'no_found_rows\'             => true, //https://wpartisan.me/tutorials/wordpress-database-queries-speed-sql_calc_found_rows
    \'update_post_term_cache\'    => false //ignore terms
);
生成此查询的:

SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND wp_posts.post_parent = 3526 AND ( ( wp_postmeta.meta_key = \'_bbp_last_active_time\' AND wp_postmeta.meta_value > \'2015-10-04 11:51:05\' ) AND ( mt1.meta_key = \'bbppu_read_by\' AND mt1.meta_value = \'1\' ) ) AND wp_posts.post_type = \'topic\' AND ((wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'closed\' OR wp_posts.post_status = \'private\')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC
在PhPMyAdmin中,此查询大约需要0.0393 seconds 并返回228个帖子。

没有Posteta内容的相同查询需要only 0.0022 秒。

SELECT wp_posts.ID FROM wp_posts WHERE 1=1  AND wp_posts.post_parent = 3526 AND wp_posts.post_type = \'topic\' AND ((wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'closed\' OR wp_posts.post_status = \'private\')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC 
这是一个巨大的区别about 18 times 更快。

我有一个用户抱怨插件速度太慢;他有一个拥有100000多个帖子的论坛。

我想知道您是否有更快的解决方案?

1 个回复
SO网友:Mark Kaplun

用户读取的内容是用户的属性,而不是主题的属性。每个用户都需要这些信息,为此,需要将值存储在用户的元中。您可能还想知道哪些用户阅读了某个主题,这样您当前的系统就不会相互排斥,但它在概念上是不好的,这会导致它的速度变慢。