0

我在 Code Igniter 模型中使用下面的代码从数据库中提取数据。但是我的数据库有 2 个 Cust_Phone 字段。我想对其进行设置,以便在用户输入电话号码时搜索电话字段。我认为有一种方法可以在 mysql 查询中使用类似的东西来做到这一点

select distinct Phone from 
(SELECT Cust_Phone1 AS Phone 
  FROM Customer

UNION

SELECT Cust_Phone2 AS Phone 
  FROM Customer) as t where Phone <> ''

在我的另一个选择查询中,但我不确定如何去做,或者我是否以正确的方式这样做。

--- CodeIgniter 模型函数 ---

public function customerQuery($First,$Last,$Zip,$Phone) {
    $sql = "SELECT * FROM Customer WHERE Cust_First LIKE ? AND Cust_Last LIKE ? AND Cust_Zip LIKE ? AND Cust_Phone1 Like ?"; 
    if($First == null || $First == '') {
        $First = '%';
    }else{
        $First = '%' . $First . '%';
    }
    if($Last == null || $Last == '') {
        $Last = '%';
    }else{
        $Last = '%' . $Last . '%';
    }
    if($Zip == null || $Zip == '') {
        $Zip = '%';
    }else{
        $Zip = '%' . $Zip . '%';
    }
    if($Phone == null || $Phone == '') {
        $Phone = '%';
    }else{
        $Phone = '%' . $Phone . '%';
    }
    $query = $this->db->query($sql, array($First,$Last,$Zip,$Phone));
    return $query->result();
}
4

2 回答 2

1

尝试这个:

$sql = "SELECT * FROM Customer WHERE Cust_First LIKE ? AND Cust_Last LIKE ? AND Cust_Zip LIKE ? AND (Cust_Phone1 LIKE ? OR Cust_Phone2 LIKE ?)";
...
...
if($Phone == null || $Phone == '') {
    $Phone = '%';
}else{
    $Phone = '%' . $Phone . '%';
}
$query = $this->db->query($sql, array($First,$Last,$Zip,$Phone,$Phone));
于 2013-03-15T17:13:01.977 回答
0

您可以像这样检查两个电话字段...

$sql = "SELECT * FROM Customer WHERE Cust_First LIKE ? AND Cust_Last LIKE ? AND Cust_Zip LIKE ? AND (Cust_Phone1 Like ? OR Cust_Phone2 Like ?)";

...

$query = $this->db->query($sql, array($First,$Last,$Zip,$Phone,$Phone));
于 2013-03-15T17:12:43.750 回答