Zendframework Union Issue

时间:2013-09-10 13:47:15

标签: php sql zend-framework zend-db

我运行了这段代码

$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)

工会之前的部分是$ sq,之后的部分是$ sqtemp,两者的组合给出了上面的打印输出 他们两个都结合在一起

1 个答案:

答案 0 :(得分:1)

在第二次查看您的代码后,我怀疑oder()对联盟的调用。您按cs.code_id排序,select语句中未提及任何内容,c.code_id也未提及此问题。
尝试将c.code_idcs.code_id添加到构成SELECT的{​​{1}}',可以考虑使用别名,然后您可以在{{1}中使用该别名}子句。

UNION

我认为,这应该有效。我从不同的地方获取灵感。以下是一些导致我答案的链接(无法找到所有这些链接):