Zend Framework 2 Sql选择OR和AND

时间:2013-06-21 18:39:15

标签: zend-framework2 zend-db

我想使用Zend \ Db \ Sql \ Select:

进行此查询
SELECT table1.* FROM table1 
    INNER JOIN table2 ON table1.columnA = table2.columnB 
    INNER JOIN table3 ON table1.columnC = table3.columnD

WHERE (table2.column2 = 2 or table3.column3 = 3) and table1.column1 = 1

ORDER BY table1.columnE ASC LIMIT 1

到目前为止我有这个代码:

/*@var $db Adapter */
$db = $this->getServiceLocator()->get('db');
$sql = new Sql($db);
$select = $sql->select();

$select->from('table1');
$select->join('table2','table1.columnA = table2.columnB',array());
$select->join('table3','table1.columnC = table3.columnD',array());

$select->where(array('table2.column2' => 2, 'table2.column3' => 3), Predicate\PredicateSet::OP_OR);

$select->where(array('table1.column1' => 1),Predicate\PredicateSet::OP_AND);

$select->order('table1.columnE ASC');
$select->limit(1);

$statement = $sql->prepareStatementForSqlObject($select);
$resultSet = $statement->execute();

但是不起作用,因为产生这个(没有“(”和“)”为OR):

SELECT table1.* FROM table1 
    INNER JOIN table2 ON table1.columnA = table2.columnB 
    INNER JOIN table3 ON table1.columnC = table3.columnD

WHERE table2.column2 = 2 or table3.column3 = 3 and table1.column1 = 1

ORDER BY table1.columnE ASC LIMIT 1

我该怎么办?

2 个答案:

答案 0 :(得分:36)

从头顶使用Where fluent interface:

$select->where
       ->nest
           ->equalTo('table2.column2', 2)
           ->or
           ->equalTo('table2.column3', 3)
       ->unnest
       ->and
       ->equalTo('table1.column1', 1);

答案 1 :(得分:7)

我会做类似的事情:

$where = new \Zend\Db\Sql\Where();

$where
    ->nest()
    ->equalTo('table2.column2', 2)
    ->or
    ->equalTo('table2.column3', 3)
    ->unnest()
    ->and
    ->equalTo('table1.column1', 1);
$select->where($where)

正因为这样你的$ select继续作为Zend \ Db \ Sql \ SqlInterface的实现 在做的时候

$select->where
   ->nest

将返回Zend Sql运算符的实例。哪个不坏但是你不能做

$statement = $sql->prepareStatementForSqlObject($select);
$resultSet = $statement->execute();