我需要在过去30天内提交最多订单。 max field是一个virtualField。
public $virtualFields = array(
'max_submitted' => "MAX(`WorkRecord`.`submitted`)"
);
I get error #1054 - Unknown column 'WorkRecord.max_submitted' in 'field list'
SELECT `WorkRecord`.`id`, `Order`.`fee`, `Order`.`order_id`,
`Order`.`min_sources`, `Order`.`min_references`, `Order`.`am_level`,
`Order`.`am_standard`, `Order`.`am_type`, `Order`.`am_subject`, `Order`.`am_word_count`,
`Order`.`ref_style`, `Order`.`service`, `BriefInstalment`.`deadline`,
`BriefInstalment`.`id`, (MAX(`WorkRecord`.`submitted`)) AS `WorkRecord__max_submitted`
FROM `writers`.`work_records` AS `WorkRecord`
RIGHT JOIN `torg`.`temp_orders` AS `Order` ON (`Order`.`order_id` = `WorkRecord`.`order_id` AND `Order`.`status2` > 2 AND `Order`.`am_type` NOT LIKE '%phd%') LEFT JOIN `writers`.`brief_instalments` AS `BriefInstalment` ON (`WorkRecord`.`brief_instalment_id` = `BriefInstalment`.`id`)
WHERE `WorkRecord`.`writer_id` = 7827
AND `WorkRecord`.`withdrawn` IS NULL
AND `WorkRecord`.`max_submitted` BETWEEN NOW() - INTERVAL 30 DAY AND NOW() GROUP BY `Order`.`order_id`
答案 0 :(得分:0)
您不能在where
子句中使用聚合函数结果,因为在应用where子句时,聚合的结果(例如max()
)将不可用。
将max()移动到`having:
SELECT ..., max(foo) AS foo
FROM ...
WHERE ...
HAVING foo BETWEEN ...
having
基本上应用于通过客户端发送结果之前的最后一步。到那时,所有的计算/聚合都已完成。
答案 1 :(得分:0)
对于其他人。这是我应该做的。
$workRecords = $this->find('all', array(
'fields' => array(
'WorkRecord.id', 'MAX(`WorkRecord`.`submitted`) AS submitted',
'Order.fee', 'Order.order_id', 'Order.min_sources', 'Order.min_references', 'Order.am_level', 'Order.am_standard',
'Order.am_type', 'Order.am_subject', 'Order.am_word_count', 'Order.ref_style', 'Order.service'
),
'conditions' => array(
'WorkRecord.writer_id' => $userId,
'WorkRecord.withdrawn IS NULL'
),
'joins' => array(
array(
'table' => 'torg.temp_orders',
'alias' => 'Order',
'type' => 'RIGHT',
'conditions' => array(
'Order.order_id = WorkRecord.order_id',
'Order.status2 >' => 2,
"Order.am_type NOT LIKE '%phd%'"
)
)
),
'contain' => array(
'BriefInstalment.deadline'
),
'group' => array(
'Order.order_id HAVING `submitted` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()'
)
));