我有这段代码正在运行
$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,两者的组合给出了上面的打印输出