【问题标题】:MySQL Union Losing Table NamesMySQL Union 丢失表名
【发布时间】: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 的可能重复项

标签: php mysql join union


【解决方案1】:
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%')

【讨论】:

  • 您的 SQL 语法有误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的 'AND (a.lastname LIKE 'crea%' OR b.busname LIKE 'crea%')' 附近使用正确的语法
  • aah.. 我在查询中遗漏了一些内容...更新了查询.. 请立即尝试。
  • did 从客户中选择 a.lastname , b.busname 作为内部连接 ​​busclients 作为 b on busclients.agentid = clients.agentid where a.agentid = '$agentid' AND (a.lastname LIKE ' $q%' OR b.busname LIKE '$q%') 并在 'on 子句' 中得到未知列 'busclients.agentid',但 agentid 存在于两个表中。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2015-11-10
    • 2015-10-06
    • 1970-01-01
    相关资源
    最近更新 更多