Zend Framework 1在使用union()时不能使用where()方法

时间:2014-07-31 07:53:45

标签: php zend-framework

$select = $logAdapter->select(); // an instance of Zend_Db_Select class
$select->union(array(
         "SELECT Country,Name
          FROM ManualLog_TheNew",
         "SELECT Country,Name
          FROM ManualLog_TheOld"),Zend_Db_Select::SQL_UNION_ALL);
$select->order("$param->orderBy")
         ->limit($param->length,$param->offset);

这项工作,但是当我在where()之前插入$select->order()方法时,会抛出错误。

$select->where('ManualLog_TheOld.OperateTime >= ?' => "2014-06-30");

错误是:

<b>Fatal error</b>:  Uncaught exception 'Zend_Db_Select_Exception' with message 'Invalid use of where clause with UNION' in /xxx/code/ZendFramework/Zend/Db/Select.php:880

我已经沮丧了大约两天,请帮助我。谢谢。

@Claudio Venturini

我尝试了你的答案,还有两个问题:

1打印出的sql是:

Warning: strpos() expects parameter 1 to be string, array given in /code/ZendFramework/Zend/Db/Select.php on line 739
Warning: explode() expects parameter 2 to be string, array given in /code/ZendFramework/Zend/Db/Select.php on line 740
Warning: strpos() expects parameter 1 to be string, array given in /code/ZendFramework/Zend/Db/Select.php on line 739
Warning: explode() expects parameter 2 to be string, array given in /code/ZendFramework/Zend/Db/Select.php on line 740
SELECT `ManualLog_TheOld`.`Country` 
FROM `` AS `ManualLog_TheOld` 
WHERE (OperateTime >= '2014-06-30') 
UNION ALL 
SELECT `ManualLog_TheNew`.`Country` 
FROM `` AS `ManualLog_TheNew` 
WHERE (OperateTime >= '2014-06-30') 
ORDER BY `OperateTime` desc LIMIT 200

如何删除from ``...as

2当我删除from `` ... as并执行sql时,我收到以下错误:

Error Code: 1054
Unknown column 'ManualLog_TheNew.OperateTime' in 'order clause'

但我有OperateTime字段!怎么了?

PS:我已经知道了,我也应该查询OperateTime字段。

1 个答案:

答案 0 :(得分:1)

您无法在外部WHERE查询中使用UNION条件。您只能在WHERE

中的任何子查询中使用UNION

例如,这是有效的SQL

(SELECT Country,Name
    FROM ManualLog_TheNew
    WHERE condition1)
UNION
(SELECT Country,Name
    FROM ManualLog_TheOld
    WHERE condition2)

以下内容无效:

(SELECT Country,Name FROM ManualLog_TheNew)
UNION
(SELECT Country,Name FROM ManualLog_TheOld)
WHERE condition

请参阅UNION上的文档以供参考:http://dev.mysql.com/doc/refman/5.5/en/union.html

因此,要在每个条件中以编程方式添加相同的WHERE条件,您必须单独创建每个SELECT语句。请尝试以下方法:

$condition = 'OperateTime >= ?';
$conditionValue = '2014-06-30';

$selectOld = $logAdapter->select();
$selectOld->from(array('ManualLog_TheOld'), array('Country', 'Name'))
$selectOld->where($condition, $conditionValue);

$selectNew = $logAdapter->select();
$selectNew->from(array('ManualLog_TheNew'), array('Country', 'Name'))
$selectNew->where($condition, $conditionValue);

$select = $logAdapter->select();
$select->union(array($selectOld, $selectNew), Zend_Db_Select::SQL_UNION_ALL);

$select->order($param->orderBy)->limit($param->length, $param->offset);