MYSQLI行计算太慢

时间:2015-05-26 23:51:58

标签: php mysql mysqli count rows

我正在尝试使用带有MYSQLI的SQL_CALC_FOUND_ROWS来计算我桌子上的访问者,但它很慢。它超过15秒。我能做什么让它更快? 我必须提到我的桌子是MyISAM,总共超过200万行。

if ($result = $mysqli->query("SELECT SQL_CALC_FOUND_ROWS *  FROM visitors_table WHERE visitor_affiliate= 'first user'")) {
    /* determine number of rows result set */

     $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}


 if ($result2 = $mysqli->query("SELECT SQL_CALC_FOUND_ROWS *  FROM visitors_table WHERE visitor_affiliate= 'seconduser'")) {
        /* determine number of rows result set */

         $row_cnt2 = $result2->num_rows;

        printf("Result set has %d rows.\n", $row_cnt2);

        /* close result set */
        $result2->close();
    }

 if ($result3 = $mysqli->query("SELECT SQL_CALC_FOUND_ROWS *  FROM visitors_table WHERE visitor_affiliate= 'thirduser'")) {
        /* determine number of rows result set */

         $row_cnt3 = $result3->num_rows;

        printf("Result set has %d rows.\n", $row_cnt3);

        /* close result set */
        $result2->close();
    }

任何帮助表示赞赏.. 提前谢谢!

1 个答案:

答案 0 :(得分:0)

确保列visitor_affiliate:

上有索引
CREATE INDEX aff_index ON visitors_table(visitor_affiliate) ;

然后您需要一个查询来获得三个结果:

SELECT visitor_affiliate, COUNT(*) AS tot FROM visitors_table 
 WHERE visitor_affiliate IN ( 'firstuser',  'seconduser',  'thirduser')
 GROUP BY visitor_affiliate 

通常比三个查询更快。

如果您仍需要分开的查询:

SELECT COUNT(*) AS tot FROM visitors_table 
WHERE visitor_affiliate IN = 'firstuser'