没有所谓的捷径
一切都是时间最平凡的累积

WordPress数据量很大时, 解决SQL_CALC_FOUND_ROWS查询使网站变慢问题

本文最后更新:2020年4月24日,已超过1434天未更新,如果文章内容失效,请留言反馈本站。

WordPress在查询post列表时,默认会同时把文章数量也查询出来,

使用这种方式的有:get_posts 、query_postsWP_Query

get_posts在4.6.1+已经不用SQL_CALC_FOUND_ROWS,但是query_postsWP_Query还是会用,所以还须优化。

具体语句如下:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' ) ORDER BY wp_posts.post_date DESC LIMIT 0, 20
SELECT FOUND_ROWS()

这在网站数据量小的时候,不会引起什么问题,

但是当post数量到10w+的时候,这个就是一条必现的慢查询

首页、分类、标签、搜索页面,只要用到这几个函数,就都会使用SQL_CALC_FOUND_ROWS这个方式。

那么,如何解决?

禁用掉SQL_CALC_FOUND_ROWS用法,用一种更加高效的方式,

这里我们用EXPLAIN方式,为什么用EXPLAIN而不是count(*)?

具体代码如下,放在functions.php文件:

if ( ! function_exists( 'maizi_set_no_found_rows' ) ) {
    /**
     * 设置WP_Query的 'no_found_rows' 属性为true,禁用SQL_CALC_FOUND_ROWS
     *
     * @param  WP_Query $wp_query WP_Query实例
     * @return void
     */
    function maizi_set_no_found_rows(\WP_Query $wp_query)
    {
        $wp_query->set('no_found_rows', true);
    }
}
add_filter( 'pre_get_posts', 'maizi_set_no_found_rows', 10, 1 );


if ( ! function_exists( 'maizi_set_found_posts' ) ) {
    /**
     * 使用 EXPLAIN 方式重构
     */
    function maizi_set_found_posts($clauses, \WP_Query $wp_query)
    {
        // Don't proceed if it's a singular page.
        if ($wp_query->is_singular()) {
            return $clauses;
        }

        global $wpdb;

        $where = isset($clauses['where']) ? $clauses['where'] : '';
        $join = isset($clauses['join']) ? $clauses['join'] : '';
        $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : '';

        $wp_query->found_posts = (int)$wpdb->get_row("EXPLAIN SELECT $distinct * FROM {$wpdb->posts} $join WHERE 1=1 $where")->rows;

        $posts_per_page = (!empty($wp_query->query_vars['posts_per_page']) ? absint($wp_query->query_vars['posts_per_page']) : absint(get_option('posts_per_page')));

        $wp_query->max_num_pages = ceil($wp_query->found_posts / $posts_per_page);

        return $clauses;
    }
}
add_filter( 'posts_clauses', 'maizi_set_found_posts', 10, 2 );

参考资料:

  1. WordPress: SQL_CALC_FOUND_ROWS, why it’s slow and what to do about it
  2. Speed up WordPress WP_Query and query_posts functions
» 站长码字辛苦,有用点个赞吧,也可以打个
» 若转载请保留本文转自:豫章小站 » 《WordPress数据量很大时, 解决SQL_CALC_FOUND_ROWS查询使网站变慢问题》
» 本文链接地址:https://mydns.vip/2766.html
» 如果喜欢可以: 点此订阅本站 有需要帮助,可以联系小站
赞(3) 打赏
声明:本站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,若涉及侵权请及时告知,将会在第一时间删除,联系邮箱:contact@mydns.vip。文章观点不代表本站立场。本站原创内容未经允许不得转载,或转载时需注明出处:豫章小站 » WordPress数据量很大时, 解决SQL_CALC_FOUND_ROWS查询使网站变慢问题
分享到: 更多 (0)

评论 抢沙发


  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

智慧源于勤奋,伟大出自平凡

没有所谓的捷径,一切都是时间最平凡的累积,今天所做的努力都是在为明天积蓄力量

联系我们赞助我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏