如何在下面翻译为cakePHP代码?以下代码来自此处MySQL order by before group by的解决方案。
使用group by获取作者的最新帖子。
SELECT p1.*
FROM wp_posts p1
INNER JOIN
(
SELECT max(post_date) MaxPostDate, post_author
FROM wp_posts
WHERE post_status='publish'
AND post_type='post'
GROUP BY post_author
) p2
ON p1.post_author = p2.post_author
AND p1.post_date = p2.MaxPostDate
WHERE p1.post_status='publish'
AND p1.post_type='post'
order by p1.post_date desc
下面仍然是类似的情况:
SELECT t1.* FROM payment_status t1
JOIN (SELECT payment_id, MAX(created) max_created
FROM payment_status
GROUP BY payment_id
) t2
ON t1.payment_id = t2.payment_id AND t1.created = t2.max_created;
我需要对两个mySQL语句进行一些cakePHP翻译。
我做了类似下面的代码,但它给了我错误
错误:SQLSTATE [42000]:语法错误或访问冲突:1059标识符名称' SELECT max(dateEncoded)maxDate,发现FROM维护GROUP BY computer_id Office.main_office LIKE'太长了
如何解决?
$this->Computer->unbindModel(array(
'belongsTo' => array('Office'),
'hasMany' => array('Brand','Maintain')
));
$model_view = $this->Computer->bindModel(array(
'hasOne' => array(
'Office' => array(
'foreignKey' => false,
'conditions' => array('Office.id = Computer.office_id')
),
'Maintain' => array(
'foreignKey' => false,
'conditions' => array('Computer.id = Maintain.computer_id'),
)
)
)
);
$main_office = trim($this->request->data['Office']['office_id']);
$joins = array(
array(
'table' => "SELECT max(dateEncoded) maxDate, findings FROM maintain GROUP BY computer_id",
'alias' => 'P2',
'type' => 'INNER',
'conditions' => array('Maintain.findings = p2.findings','Maintain.dateEncoded = p2.maxDate')
)
);
$conditions=array("Office.main_office LIKE"=>"%$main_office%");
$result = $this->Computer->find('all',array(
$model_view,
'joins'=>$joins,
'conditions'=>$conditions,
'order' => array('Office.description'),
'group' => 'Computer.id'
));
答案 0 :(得分:0)
这可以这样写: -
$joins = array(
array(
'table' => 'SELECT max(post_date) MaxPostDate, post_author FROM wp_posts WHERE post_status='publish' AND post_type='post'GROUP BY post_author',
'alias' => 'P2',
'type' => 'INNER',
'conditions' => array('WpPost.post_author = p2.post_author','WpPost.post_date = p2.MaxPostDate')
)
);
$conditions=array("WpPost.post_status='publish'","WpPost.post_type='post'");
$this->WpPost->find('all',array('fields'=>array('WpPost.*'),'joins'=>$joins,'conditions'=>$conditions);