[英]Convert SQL satement to Zend Db_Table_Abstract_Select code
我正在嘗試從下表中獲取每個客戶的最新行。
----------------------------------------------------------------------------------
| id | customer_id | type | type_id | notes | timestamp | uid |
----------------------------------------------------------------------------------
| 1 | 1 | sales | 9 | Note 1... | 1432781613 | 9 |
| 2 | 2 | sales | 9 | Note 1... | 1432791204 | 9 |
| 3 | 3 | sales | 9 | Note 1... | 1432881619 | 9 |
| 4 | 1 | sales | 9 | Note 2... | 1442771601 | 9 |
| 5 | 1 | sales | 9 | Note 3... | 1462781617 | 9 |
我有以下代碼和有效的SQL語句...
$type="sales";
$sql = "
SELECT cl1.*
FROM {$this->_name} cl1
INNER JOIN (
SELECT customer_id, MAX(timestamp) AS lastTimestamp
FROM {$this->_name}
WHERE type = '{$type}'
GROUP BY customer_id
) cl2
ON cl1.customer_id = cl2.customer_id AND cl1.timestamp = cl2.lastTimestamp
";
$stmt = $this->getAdapter()->query($sql);
產生...
SELECT cl1.* FROM customer_contactLog cl1 INNER JOIN ( SELECT customer_id, MAX(timestamp) AS lastTimestamp FROM customer_contactLog WHERE type = 'sales' GROUP BY customer_id ) cl2 ON cl1.customer_id = cl2.customer_id AND cl1.timestamp = cl2.lastTimestamp
我試圖將其轉換為“ Zend方式”,因為我所有其他模型都是以這種方式編寫的,但是我很掙扎。 我想出的代碼是...
$select = $this ->select()
->from (
array('cl1' => $this->_name),
array('cl1.*')
)
->join (
array('cl2' => $this->_name),
"cl2.type = '{$type}'",
array('cl2.customer_id', 'MAX(cl2.timestamp) AS lastTimestamp')
)
->where ('cl1.customer_id = ?', 'cl2.customer_id')
->where ('cl1.timestamp = ?', 'cl2.lastTimestamp');
但這產生了...
SELECT `cl1`.*, `cl2`.`customer_id`, MAX(cl2.timestamp) AS `lastTimestamp` FROM `customer_contactLog` AS `cl1` INNER JOIN `customer_contactLog` AS `cl2` ON cl2.type = 'sales' WHERE (cl1.customer_id = 'cl2.customer_id') AND (cl1.timestamp = 'cl2.lastTimestamp')
誰能告訴我我要去哪里錯了?
謝謝
您可以在Zend DB查詢中使用嵌套選擇。 這正是您所需要的-創建一個子選擇,然后將其加入主選擇中。
$maxTimestampSelect = $this->select()
->from(
$this->_name,
array('customer_id', 'lastTimestamp' => new Zend_Db_Expr('MAX(timestamp)'))
)
->where('type = ?', $type)
->group('customer_id');
$select = $this->select()
->from(
array('cl1' => $this->_name),
array('cl1.*')
)
->join(
array('cl2' => $maxTimestampSelect),
'cl1.customer_id = cl2.customer_id AND cl1.timestamp = cl2.lastTimestamp',
null
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.