Zend DB联合计数

时间:2016-10-18 13:52:36

标签: php zend-db

我有两个选择,它们是联合的,类似这样:

$select->from ( array (
                'A' => 'tableA' 
        ), array (
                'field1',
                .....
        ) );
$select2->from ( array (
                'B' => 'tableB' 
        ), array (
                'field1',
                .....
        ) );
$select3 = $this->getAdapter()->select ()
            ->union(array($select1, $select2));

现在,基于联盟,我想这样做:

$select3->reset ( 'columns' )->columns ( new Zend_Db_Expr ( 'COUNT(DISTINCT(field1))' ))

但是我收到了这个错误:

  

没有为FROM子句指定表

这在技术上是正确的,但我不想从表中计算,我想从我的联盟中的结果计数。我该怎么做?

1 个答案:

答案 0 :(得分:0)

我最终像这样工作:

$select3->reset ( 'columns' );//->columns ( new Zend_Db_Expr ( 'COUNT(DISTINCT(field1))' ))
$sql = $select->__toString();
        $countQuery = <<<EOD
SELECT COUNT(DISTINCT(res.field1)) as total_rows FROM ($sql) as res
EOD;


        $countResult = $this->getAdapter ()->query($countQuery)->fetchAll();

        $count = 0;

        if (! empty ( $countResult )) {
            $count = $countResult [0] ['total_rows'];
        }