類似的東西應該工作:
$subselect = $dbAdapther->select()->from(
array('test_stats' => 'test_stats'),
array(
'(COUNT(test_public_id)) AS recent_views'
)
)->where(
$dbAdapther->quoteInto('test_stats.test_public_id = ?', $tourId)
)->where(
'test_stats.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)'
);
$select = $dbAdapther->select()->from(
array('ms' => 'test_stats'),
array(
'(COUNT(ms.test_public_id)) AS total_views' // COUNT should be in brackets to preevent Zend from interpreting it as a field name
)
)->join(
array('ms1' => $subselect),
'',
array(
'ms1.recent_views'
)
)->where(
$dbAdapther->quoteInto('ms.test_public_id = ?', $tourId)'
);
雖然我有你的查詢分爲兩個單獨的查詢,或者更確切地說,寫一個通用的「獲取視圖數」查詢,並將日期作爲其參數,然後我會調用它兩次,不論是否有日期。
但是如果你仍然需要在一行中一次性得到這兩個數字(即你不能使用UNION而不是你不必要的JOIN),我建議你使用下面的代碼來代替:
$select = $dbAdapther->select()->from(
array('ms' => 'test_stats'),
array(
'(COUNT(ms.test_public_id)) AS total_views',
'(
COUNT(
CASE
WHEN ms.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)) THEN ms.test_public_id
ELSE NULL
END
)
) AS recent_views'
)
)->where(
$dbAdapther->quoteInto('ms.test_public_id = ?', $tourId)
);
描述什麼「沒有工作」 - 錯誤消息,意想不到的結果等將是有用的。例如,您顯示的代碼缺少引用('$ query ='之後和'select'之前),但可能會只是一個錯字。更多信息會很好。 – StasM