如何使用DISTINCT
获取total_time_driven_at_this_trip
最高价值的唯一用户ID,并从另一个基于user_name
的关系表中提取user_id
?< / p>
我试过了......
$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
答案 0 :(得分: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')
));
}
答案 1 :(得分:7)
在cakephp中纠正DISTINCT关键字的语法
$this->set('banners', $this->Banner->find('all',array('fields'=>'DISTINCT Banner.id')));
确保DISTINCT在字段数组中使用。
答案 2 :(得分:1)
正确的语法是
$this->set('tripNsws', $this->TripNsw->find('all',array('fields'=>'DISTINCT TripNsw.user_id')));
答案 3 :(得分:1)
您可以考虑将其设置为虚拟字段(http://book.cakephp.org/1.3/view/1608/Virtual-fields)
$this->Model->virtualFields['distinct_user'] = 'DISTINCT Model.user_id';
答案 4 :(得分:0)
我总是在查询中使用GROUP BY来获得与DISTINCT
相同的结果答案 5 :(得分:0)
'fields' => array('DISTINCT Model.Modelfield')
或
'fields' => array('Model.id','DISTINCT Model.Modelfield')