我正在学习CakePHP,但是我在使用更复杂的数据库查询时遇到了很大问题。 所以我想执行这种查询:
SELECT p.name, b.value
FROM books b LEFT JOIN projects p
ON b.project_id=p.id
WHERE b.created=
(SELECT max(b.created) FROM books b WHERE b.user_id=1)
AND b.user_id=1
GROUP BY p.name
有人可以帮我用cakePHP机制编写这个来准备查询吗?
答案 0 :(得分:3)
您的代码应与此类似,假设Book e Project处于关系中(Book
belongsTo Project
)
$this->Book->find
(
'all',
array
(
'fields' => array('Book.value', 'Project.name'),
'conditions' => array
(
'Book.created IN (SELECT MAX(Book.created) FROM books Book WHERE Book.user_id = 1)',
'Book.user_id' => 1
),
'group' => 'Project.name'
)
);
答案 1 :(得分:0)
使用IN子句。
SELECT p.name, b.value
FROM books b
LEFT JOIN projects p ON b.project_id=p.id
WHERE b.created IN (SELECT max(created) FROM books WHERE user_id=1)
AND b.user_id=1
GROUP BY p.name
答案 2 :(得分:0)
如果Book和Projects是Models,您可以使用Book模型直接使用CakePHP函数进行连接,请参阅https://stackoverflow.com/a/16286735/2858188
答案 3 :(得分:0)
请参阅此链接http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries以按照cakephp约定编写子查询。