我正在使用 Codeigniter + MySQL。我想打印一个部分中每个类别的记录数。我有一个广告表、类别表和部分表。这是我的代码:
foreach($categories as $category){
$query = $this->db->query(" SELECT count(*) AS total_ads from ads where categoryid = $category->id and ( status = 1 OR status = 3 ) and sectionid = $section->id");
$count_row = $query->row();
$count = $count_row->total_ads;
}
广告总数约为 62138 个(记录)。 但服务器响应时间太长(大约 4 秒)。有没有什么可以加快这段代码的速度,我的意思是进行更改以优化。
最佳答案
尝试在数据库中创建新索引:
CREATE INDEX cat_sec_status ON ads (categoryid, sectionid, status);
并将代码更改为:
$query = $this->db->query("
SELECT COUNT(id) AS total_ads, categoryid
FROM ads
WHERE categoryid IN $categorysIds
AND sectionid = $section->id
AND status IN (1,3)
GROUP BY categoryid
");
$count_row = $query->row();
在变量 $categorysIds 中,以“(1,2,3,4,5)”格式存储所有类别 ID。 这段代码不需要 foreach。
更新: 最终的代码可能是这样的:
// Extract categories Ids into array
$categoriesIds = array_map(function($object) {return $object->id;}, $categories);
// prepare array to SQL statement
$categoriesIdsCondition = '(' . implode(',', $catIds) . ')';
// 'Good' statuses
$enabledStatuses = array(1, 3);
$enabledStatusesCondition = '(' . implode(',', $enabledStatuses) . ')';
// Get records count of every category
$query = $this->db->query("
SELECT COUNT(id) AS total_ads, categoryid
FROM ads
WHERE categoryid IN $categoriesIdsCondition
AND sectionid = $section->id
AND status IN $enabledStatusesCondition
GROUP BY categoryid
");
// If there is any records, store them
if ($query->num_rows() > 0)
{
$adsCounter = $query->result();
}
// Usage example
foreach($adsCounter as $categoryAds){
echo "In the category with ID =
. {$categoryAds->categoryid}
. there are
. {$recordsCounter->total_ads}
. records";
}
关于php - 优化 CI 中的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778211/