0

我有这段代码正在运行

$sq = $this->_codes->getAdapter()->select()
            ->from (array('cs' => 'code_statuses'), array('total' =>     'count(*)'))
            ->join (
                array ('c' => 'codes'), 'c.code_id = cs.code_id', 
                array ('human_state' => new Zend_Db_Expr("CASE c.state_id WHEN 3 THEN 'active' WHEN 5 THEN 'suspended' ELSE 'inactive' END"), 'c.*')
            )
            ->group('cs.code_id');

$sqtemp = $this->_codes->getAdapter()->select()
            ->from (array('cs' => 'code_statuses'), array('total' => 'count(*)'))
            ->join (
                array ('c' => 'codes'), 'c.code_id = cs.code_id', 
                array ('human_state' => new Zend_Db_Expr("CASE     c.state_id WHEN 3 THEN 'active' WHEN 5 THEN 'suspended' ELSE 'inactive' END"), 'c.*')
            )
            ->group('cs.code_id');

if (!empty($options['state_id'])):
            if (is_array($options['state_id'])):
                $states = 'cs.state_id=' . implode(' OR cs.state_id=', $options['state_id']);
                $sq->where($states)
                                       ->having(total<=4);
                $sqtemp->where ('cs.state_id=5')
                                            ->having(total<4);
            else:
                $sq->where ('cs.state_id=?', $options['state_id']);
            endif;

当我尝试使用 union 时出现问题

$sqfinal=$this->_codes->getAdapter()->select()
                ->union(array($sq,$sqtemp))
                ->order('cs.code_id');

但单独$sq$sqtemp工作正常

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cs.code_id' in 'order clause'

不知道我哪里错了

任何帮助将不胜感激

*编辑

SELECT count(*) AS `total`, 
CASE c.state_id 
WHEN 3 THEN 'active' 
WHEN 5 THEN 'suspended' 
ELSE 'inactive' 
END AS `human_state`, `c`.* 
FROM `code_statuses` AS `cs` 
INNER JOIN `codes` AS `c` 
ON c.code_id = cs.code_id 
WHERE (cs.state_id=1 OR cs.state_id=2 OR cs.state_id=4) 
GROUP BY `cs`.`code_id` HAVING (total<=4) 
UNION 
SELECT count(*) AS `total`, 
CASE c.state_id 
WHEN 3 THEN 'active' 
WHEN 5 THEN 'suspended' 
ELSE 'inactive' 
END AS `human_state`, `c`.* 
FROM `code_statuses` AS `cs` 
INNER JOIN `codes` AS `c` 
ON c.code_id = cs.code_id 
WHERE (cs.state_id=5) 
GROUP BY `cs`.`code_id` 
HAVING (total<4)

union 之前的部分是 $sq,之后的部分是 $sqtemp,两者的组合给出了上面的打印输出

4

1 回答 1

1

再次查看您的代码后,我怀疑oder()工会的电话。您按 订购,任何陈述cs.code_id中均未提及,也未提及。 尝试添加或添加到组成 的 't 中,可能考虑使用别名,然后您可以在子句中使用该别名。selectc.code_id
c.code_idcs.code_idSELECTUNIONorder

$sq = $this->_codes->getAdapter()->select()
            ->from(array('cs' => 'code_statuses'),
                   array(
                       'total'     => 'count(*)'
                       'cscodeids' => 'code_ids',
                   ));
//...
$union = $this->_codes->getAdapter()
              ->select()
              ->union(array($sq,$sqtemp))
              ->order('cscodeids');

我相信这应该有效。我从不同的地方获得了灵感。以下是导致我回答的一些链接(无法找到所有这些 ATM):

于 2013-09-11T11:58:57.113 回答