0
我有两个php函数执行相当缓慢,因为我有一个大型数据库。一个请求类别名称。另一个做子类别计数。下面,我试图转换到SQL来加快查询,但不知道如何解决foreach循环,或者如果这是最有效的SQL查询方法。感谢您的反馈。将foreach php查询转换为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;
}
谢谢
问题是...? – samayo
是否有更有效的方法来执行查询,并且我可以避免在foreach循环中进行SQL查询... – gabbo876
为什么不在sql语句中使用'$ catid'?你的第二个Rwrite to SQL工作正常吗? – kero