【发布时间】:2014-03-05 16:58:11
【问题描述】:
我有一个 MySQL 查询,我试图同时搜索 2 个表。这是用于搜索普通客户和商业客户的自动完成搜索框。代码如下:
$query = mysql_query("SELECT * FROM clients WHERE lastname LIKE '$q%' AND agentid = '$agentid'
UNION
SELECT * FROM busclients WHERE busname LIKE '$q%' AND agentid = '$agentid'")or die(mysql_error());
if($query) {
while ($result = mysql_fetch_array($query)) {
$busname = $result['busname'];
print_r($result);
if(isset($busname)){
$description['id'] = 'viewbusiness.php?id=' . $result['ID'];
$description['value'] = $busname ;
array_push($return_arr,$description);
}
else
{
$description['id'] = 'viewclient.php?id=' .$result['ID'];
$description['value'] = $result['lastname'] . ", " . $result['firstname'] ;
array_push($return_arr,$description);
}
}
}
问题是业务客户端从常规客户端获得表名,因此代码从不使用 if(isset($busname)) 因为 busname 改为 lastname,并将您定向到 veiwclient 页面。
【问题讨论】:
-
您可能需要更改查询以使用 JOIN,以便 busname 和 lastname 在输出中成为单独的字段。
-
MySQL join on 2 tables 的可能重复项