简而言之:在多个数组上使用 PHP 数组 count() 是否比多次使用 SQL 行数更快?
我遇到了归因于 COUNT(*) 函数的慢速查询问题。我将解释我在做什么,然后我预期的可能会明显更快。
目前我正在循环一个函数,每次迭代计算大约 20,000 行。它返回一年中每个月的行数:
// CREATE MONTHLY LINKS
public function monthly_links() {
$months = array('','January','February','March','April','May','June','July','August', 'September','October','November','December');
for ($i=1 ; $i <= 12 ; $i++) {
$array[] = "<a href='monthly.php?month=" . $i . "&status=3'>" . $months[$i] . " " . $this->chosen_year() . " (" . $this->number_positions_month_year($i, $this->chosen_year()) . ")</a>";
}
return $array;
}
// SHOW NUMBER OF POSITIONS FOR EACH MONTH/YEAR
public function number_positions_month_year($month, $year) {
$sql = $this->client_positions_sql() . " AND MONTH(`exp_date`) = " . $month . " AND YEAR(`exp_date`) = " . $year;
$res = $this->conn->query($sql);
$count = $res->num_rows;
return $count;
}
代码在上面的示例中并不那么重要,因为基本上我要问的是:执行以下操作是否更快......?
- 查询表一次,同时将每个月对应的 id 转储到一个数组中(会有 12 个数组)
- 在每个数组上使用 PHP count() 来获取每个月的条目数