如何将这两个查询合并为一个查询?

时间:2012-08-23 14:17:15

标签: php mysql mysqli

以下是我的代码中的代码段:

$other_query = $this -> db -> query("SELECT EXISTS(SELECT 1 FROM shops WHERE cid=$cid AND zbid!=0 AND zbid!=$zbid)",__LINE__,__FILE__);
$this -> db -> output_vars["other_shops"] = $this -> db -> get_result($other_query); // 1 = there are other shops, 0 = no other shops
if($group["shop_create"] == 0){
    $my_shop = 3;
} else {            
    $my_shop_query = $this -> db -> query("SELECT EXISTS(SELECT 1 FROM shops WHERE cid=$cid AND zbid=$zbid LIMIT 1)",__LINE__,__FILE__);
    $my_shop = $this -> db -> get_result($my_shop_query) == 1 ? 1 : 2;
}

我想将两个查询合并为一个。两个查询之间的唯一区别是,一个检查zbid!=0 AND zbid!=$zbid行,而另一个检查zbid=$zbid行。这里的另一个问题是if语句。此外,在$group["shop_create"] == 0的情况下(即在此初始代码中,只运行一个查询),我不希望组合查询执行任何额外的工作。

对于那些好奇的人,$this -> db -> get_result($query_resource)基本上返回相当于mysql_result($query_resource,0)的人。我从mysql切换到mysqli时添加了此功能。

我希望这是有道理的!

1 个答案:

答案 0 :(得分:0)

为什么不这样做: “SELECT zbid FROM shops WHERE cid = $ cid”?

然后你需要等效的mysql_fetch_ *来循环结果。 就个人而言,我将它们存放在阵列和放大器中。之后进行测试。

这样的事情:

$res = $this -> db -> query("SELECT zbid FROM shops WHERE cid=$cid",__LINE__,__FILE__);
$arr = array();
while ( $row = mysql_fetch_row($res) ) {
  $arr[] = $row[0];
}
$arr = array_diff($arr, array(0));

$this -> db -> output_vars["other_shops"] = count(array_diff($arr, array($zbid)) > 0 ? 1 : 0;

if($group["shop_create"] == 0){
    $my_shop = 3;
} else {            
    $my_shop = in_array($zbid, $arr) ? 1 : 2;
}