$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
字段。
答案 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);