2013-10-08 92 views
0

我',學習CakePHP,但我有一個與更復雜的數據庫查詢操作很大的問題。 所以我想執行該類型的查詢: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

您是否試圖在此SQL語句的Book模型上使用find()方法? – AgRizzo

回答

3

你的代碼應該與此類似,假設圖書電子工程是關係(Book屬於關聯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' 
    ) 
); 
+0

太棒了,我認爲這是我一直在尋找的東西:) Thx – bbbb

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