2011-07-14 61 views
7

如何使用DISTINCT獲取具有最高值的唯一用戶ID爲total_time_driven_at_this_trip,並且還從另一個基於user_id屬於關係的表中獲取user_nameCakephp DISTINCT

我想這...

$this->set('tripNsws', $this->TripNsw->find('all',array('limit' => 20,'fields' => array('DISTINCT(TripNsw.user_id)','TripNsw.total_time_driven_at_this_trip'),'group' => array('TripNsw.user_id') ,'order' => array('TripNsw.total_time_driven_at_this_trip desc')))); 

,但它不工作。

我想你需要獲得以下....

SELECT DISTINCT(user_id),`total_time_driven_at_this_trip` FROM `trip_nsws` order by `total_time_driven_at_this_trip` desc 

回答

8
// see below url 

    http://book.cakephp.org/1.3/view/1018/find 


array(
    'conditions' => array('Model.field' => $thisValue), //array of conditions 
    'recursive' => 1, //int 
    'fields' => array('Model.field1', 'DISTINCT Model.field2'), //array of field names 
    'order' => array('Model.created', 'Model.field3 DESC'), //string or array defining order 
    'group' => array('Model.field'), //fields to GROUP BY 
    'limit' => n, //int 
    'page' => n, //int 
    'offset'=>n, //int 
    'callbacks' => true //other possible values are false, 'before', 'after' 
) 



// or try this 



function some_function() { 

    $total = $this->Article->find('count'); 

    $pending = $this->Article->find('count', array('conditions' => array('Article.status' => 'pending'))); 

    $authors = $this->Article->User->find('count'); 

    $publishedAuthors = $this->Article->find('count', array(
    'fields' => 'DISTINCT Article.user_id', 
    'conditions' => array('Article.status !=' => 'pending') 
    )); 

} 
+0

我不認爲你的回答是有關的問題 - 在所有 – mark

1

正確的構造結是

$this->set('tripNsws', $this->TripNsw->find('all',array('fields'=>'DISTINCT TripNsw.user_id'))); 
7

cakephp中DISTINCT keywork的正確語法

$this->set('banners', $this->Banner->find('all',array('fields'=>'DISTINCT Banner.id'))); 

確保DISTINCT在字段數組中使用。

0

我一直使用GROUP BY查詢來獲得相同的結果DISTINCT

0
'fields' => array('DISTINCT Model.Modelfield') 

'fields' => array('Model.id','DISTINCT Model.Modelfield')