具有一个变量的多个字段的MySQL查询

时间:2013-03-15 17:09:03

标签: php mysql codeigniter

我在Code Igniter模型中使用以下代码从数据库中提取数据。但是,我的数据库有2个Cust_Phone字段。我想设置它,以便当用户输入数字时搜索电话字段。我认为有一种方法可以在mysql查询中使用像

这样的sime
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();
}

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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));