[英]Convert SQL satement to Zend Db_Table_Abstract_Select code
I'm trying to fetch the latest row for each customer from the table below. 我正在尝试从下表中获取每个客户的最新行。
----------------------------------------------------------------------------------
| 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 |
I have the following code and SQL statement which works... 我有以下代码和有效的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);
Which produces... 产生...
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
I have tried to convert this to "the Zend way" as all my other models are written that way but I am struggling. 我试图将其转换为“ Zend方式”,因为我所有其他模型都是以这种方式编写的,但是我很挣扎。 The code I have come up with is... 我想出的代码是...
$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');
But this produces... 但这产生了...
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')
Can anyone tell me where I am going wrong? 谁能告诉我我要去哪里错了?
Thanks 谢谢
You can use nested selects within Zend DB queries. 您可以在Zend DB查询中使用嵌套选择。 This is exactly what you need here - create a subselect and then join it in main one. 这正是您所需要的-创建一个子选择,然后将其加入主选择中。
$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.