代码之家  ›  专栏  ›  技术社区  ›  Mark

使用Zend_Db_Table_Abstract对WHERE子句进行分组

  •  33
  • Mark  · 技术社区  · 16 年前

    $sql = $table->select()
                 ->where('company_id = ?', $company_id)
                 ->where('client_email = ?', $client_email)
                 ->orWhere('client_email_alt = ?', $client_email);
    

    这给了我这个:

    SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND (client_email = 'email@address.com') OR (client_email_alt = 'email@address.com')
    

    但我需要它给我这个,在OR语句分组的地方:

    SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND ((client_email = 'email@address.com') OR (client_email_alt = 'email@address.com'))
    
    5 回复  |  直到 16 年前
        1
  •  57
  •   jason    16 年前

    为了实现这一点,您必须在对 where

    如果条件的两个值相同,则可以执行以下操作:

    $select->where('client_email = ? OR client_email_alt = ?', $client_email)
    

    如果字符串中有多个占位符,则DB适配器的 quoteInto 方法将用提供的值替换所有占位符。

    如果你需要分组 OR 由于每个字段的值不同,您必须手动引用这些值。这有点复杂:

    $select->where(
        $db->quoteInto('client_email = ?', $email1) . ' OR ' . $db->quoteInto('client_email_alt = ?', $email2)
    ); // $db is your instance of Zend_Db_Adapter_*
       // You can get it from a Zend_Db_Table_Abstract 
       //subclass by calling its getAdapter() method 
    
        2
  •  6
  •   Volvox    13 年前

    你可以用 getPart() 获取WHERE语句,然后连接子查询。

    $select->where('client_email = ?', $client_email)
           ->orWhere('client_email_alt = ?', $client_email);
    
    $subquery = $select->getPart(Zend_Db_Select::WHERE);
    $select ->reset(Zend_Db_Select::WHERE);
    $select ->where('company_id = ?', $company_id)
            ->where(implode(' ',$subquery));
    
        3
  •  1
  •   edi9999    11 年前

    http://framework.zend.com/apidoc/2.2/classes/Zend.Db.Sql.Predicate.Predicate.html#nest

    $table->select()
         ->where(['company_id'=> $company_id])
         ->nest
             ->where('client_email = ?', $client_email)
             ->or
             ->where('client_email_alt = ?', $client_email)
         ->unnest();
    

        4
  •  1
  •   Ernesto Allely    10 年前

    我需要合并AND/OR语句,但有条件地包括OR语句,仅在某些情况下添加它们。这个解决方案是对我所做的工作的改编,基于对公认答案的小修改。

    $sql = $table->select()
             ->where('company_id = ?', $company_id);
    
    $orWhereClauses = [];
    // We could add a conditional statement to add this statement
    $orWhereClauses[] = $db->quoteInto('client_email = ?', $email1);
    // Same applies to this statement
    $orWhereClauses[] = $db->quoteInto('client_email_alt = ?', $email2);
    
    $sql->where(implode(" OR ", $orWhereClauses));
    
        5
  •  0
  •   Truth4oll    11 年前

    首先,您可以生成子查询,然后获取“WHERE”部分并插入到主查询中

    $subquery = $db->select();
    $subquery->orWhere('a>10');
    $subquery->orWhere('b<20');
    etc..
    
    $subquery = $subquery->getPart(Zend_Db_Select::WHERE);
    $select->where(implode(' ',$subquery));
    
    推荐文章