MySQL选择使用WHERE,LIKE,OR和AND

时间:2014-02-11 10:42:48

标签: php mysql

我正在尝试使用公司名称或客户名称(名字和姓氏)搜索客户数据库。但我也需要根据它们是否处于活动/非活动/删除状态进行搜索。但我的查询似乎忽略了最后的1或2个AND语句。

这是我到目前为止所拥有的:

    if($type == 'deleted') {
        $sql = "SELECT * FROM `".self::$table_name."` 
        WHERE `company_name` LIKE '%{$id}%' 
        OR CONCAT(first_name, ' ', last_name) LIKE '%{$id}%'
        AND `deleted` = '1'";
    } elseif($type == 'inactive') {
        $sql = "SELECT * FROM `".self::$table_name."`
        WHERE `company_name` LIKE '%{$id}%' 
        OR CONCAT(first_name, ' ', last_name) LIKE '%{$id}%'
        AND `deleted` = '0' AND `status` = 'inactive'";
    } else {
        $sql = "SELECT * FROM `".self::$table_name."`
        WHERE `company_name` LIKE '%{$id}%'
        OR CONCAT(first_name, ' ', last_name) LIKE '%{$id}%'
        AND `status` = 'active' AND `deleted` = '0'";
    }

我传递了一个类型,该类型处于活动状态,非活动状态或已删除状态。如果没有通过任何内容,它将默认为活动状态。但是,因为我需要搜索公司名称,或者首字母和姓氏的CONCAT,它似乎忽略了最后几个AND语句。

当我搜索非活动时,它会带来一些结果,但包括活动/非活动/已删除的结果。我哪里错了?我知道它必须与OR有关,但我怎么能绕过它呢?

1 个答案:

答案 0 :(得分:2)

if($type == 'deleted') {
        $sql = "SELECT * FROM `".self::$table_name."` WHERE ( `company_name` LIKE '%{$id}%' OR CONCAT(first_name, ' ', last_name) LIKE '%{$id}%' ) AND `deleted` = '1'";
    } elseif($type == 'inactive') {
        $sql = "SELECT * FROM `".self::$table_name."` WHERE ( `company_name` LIKE '%{$id}%' OR CONCAT(first_name, ' ', last_name) LIKE '%{$id}%' ) AND `deleted` = '0' AND `status` = 'inactive'";
    } else {
        $sql = "SELECT * FROM `".self::$table_name."` WHERE ( `company_name` LIKE '%{$id}%' OR CONCAT(first_name, ' ', last_name) LIKE '%{$id}%' ) AND `status` = 'active' AND `deleted` = '0'";
    }

将OR条件放在()中,然后是AND语句。