我有以下查询,用于计算过去5个月内发生的订单总销售额,
> SELECT SUM(o.total), DATE(o.order_date) dateonly FROM `order` as o where (o.order_date BETWEEN last_day(NOW() - INTERVAL 5 MONTH) AND
> date_format(NOW(), '%Y-%m-%d') AND (o.order_status = "P" OR
> o.order_status = "T" OR o.order_status = "S" OR o.order_status = "D"
> )) GROUP BY month(o.order_date)
我正在尝试在zend中实现上述查询。但我坚持中间。 我的代码来自models / DbTable,
class Default_Model_DbTable_Order extends Zend_Db_Table_Abstract
{
protected $_name = 'order';
protected $_primary = 'order_id';
public function month_based_orderlist()
{
$oDb = Zend_Registry::get("db");
$whereSQL = 'o.order_id > 0';
$whereSQL .= ' AND o.status = 1';
$whereSQL .= ' AND o.order_date BETWEEN last_day(NOW() - INTERVAL 5 MONTH) AND date_format(NOW(),'.%Y-%m-%d.')';
$whereSQL .= ' AND o.order_status = "P"';
$whereSQL .= ' OR o.order_status = "T"';
$whereSQL .= ' OR o.order_status = "S"';
$whereSQL .= ' OR o.order_status = "D"';
$select = $oDb->select()
->from(
array('o' => $this->_name),
array(
'lifetimesale' => new Zend_Db_Expr('SUM(o.total)'),
'dateonly' => DATE('o.order_date')
)
)->where($whereSQL);
//echo $select; exit;
$result = $this->getAdapter()->fetchAll($select);
// print_obj($result);
return $result;
}
}
?>
我正在尝试像上面那样实现sql查询,我在这方面做错了什么。 请帮助我
答案 0 :(得分:2)
错误在这里:
.%Y-%m-%d.
修改强>
菲尔指出我的解决方案是错误的。我重新检查,他是对的。解决方案应该只是删除刻度线,并加上双引号:// assume $date is set
$whereSQL .= ' AND o.order_date BETWEEN last_day(NOW() -'
. ' INTERVAL 5 MONTH) AND date_format(NOW(), "%Y-%m-%d")';
或者,您可以使用反斜杠转义单引号并删除sting concat运算符:
... date_format(NOW(), \'%Y-%m-%d\')';
另外,我看到你正在扩展Zend_Db_Table_Abstract
,因此,你不需要这一行:
$oDb = Zend_Registry::get('db');
请忽略它,然后使用$this
。它看起来像这样(添加了GROUP BY
子句简化):
$select = $this->select()
->from($fromTable, $columns)
->where($whereSQL)
->group('month(o.order_date)');
$result = $this->fetchAll($select);
要添加GROUP BY
子句,只需执行此操作(或使用方法链接查看上面的示例):
$select->group('month(o.order_date)');
感谢Phil寻求帮助!