[英]MySQL Union Losing Table Names
我有一个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改为姓氏,并将您定向到veiwclient页面。
通过专门从该表中选择所需的列名称,并为其他列选择一个空白字符串,我相信您可以使用以下方法获得所需的结果:
SELECT firstname, lastname, '' AS busname FROM clients WHERE ... UNION SELECT '' AS firstname, '' AS lastname, busname FROM busclients WHERE ...
SELECT
a.lastname ,
b.busname
FROM clients as a
INNER JOIN
busclients as b
on b.agent_id = a.agent_id
WHERE a.agent_id = $agent_id
AND (a.lastname LIKE '$q%' OR b.busname LIKE '$q%')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.