MySQL联盟丢失表名

时间:2014-03-05 16:58:12

标签: php mysql join union

我有一个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页面。

2 个答案:

答案 0 :(得分:0)

通过专门从该表中选择所需的列名,并为其他列选择空白字符串,我相信您可以使用以下内容获得您正在寻找的结果:

SELECT firstname, lastname, '' AS busname FROM clients WHERE ... UNION SELECT '' AS firstname, '' AS lastname, busname FROM busclients WHERE ...

答案 1 :(得分:0)

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%')