我有两个执行相当缓慢的 php 函数,因为我有一个大型数据库。一个人请求类别名称。另一个进行子类别计数。下面,我尝试转换为 SQL 以加快查询速度,但不确定如何解决 foreach 循环,或者这是否是最有效的 SQL 查询方法。感谢您的反馈。
首先:
function GetCatName($catid){
global $db, $dblang, $the_cats;
foreach($the_cats as $cat){
if($cat->category_id == $catid && $cat->category_lang == $dblang)
{
$x = $cat->category_name;
}
}
return $x;
}
重写为 SQL:
function GetCatName($catid){
global $db, $dblang;
$sql = "SELECT category_name FROM ".table_categories." where category_id = ".$catid." and category_lang = ".$dblang.";";
$x = $db->get_result($sql);
return $x;
}
第二:
function GetSubCatCount($catid){
global $db, $the_cats;
$count = 0;
foreach($the_cats as $cat){
if(isset($cat->category_parent)){
if($cat->category_parent == $catid && $cat->category__auto_id <> 0 && $cat->category_lang == $dblang)
{
$count = $count + 1;
}
}
}
return $count;
}
重写为 SQL:
function GetSubCatCount($catid){
global $db, $the_cats;
$count = 0;
foreach($the_cats as $cat){
if(isset($cat->category_parent)){
$sub_cateogories = $db->get_results("SELECT * FROM ".table_categories." where category_parent = ".$cat->category__auto_id." and category_order = 0 AND category__auto_id<>0;");
$count = count($sub_cateogories);
}
}
return $count;
}
谢谢