問題描述
我是一個 yiibie,我有一個問題,我有一個名為 user_join_event 的表,它有 id(PK)
ngo_id(FK)
event_id(FK)
date_created
date_modified
作為對象,我想獲得每個月的 5 個用戶 ID(在此表中重復(fù)次數(shù)最多).像1月前5名用戶,2月前5名用戶等等,然后是這張表中年底前5名的用戶,就像一年結(jié)束后,它應(yīng)該再次給出整個月的前5名用戶.請幫我解決這個問題,如何為此編寫SQL查詢,謝謝.
公共函數(shù) actionAllstats(){$this->layout='main';$user=UserJoinEvent::model()->findAll(array('條件' =>'YEAR(date_created)=:year 和 MONTH(date_created)=:month','參數(shù)' =>數(shù)組(':year'=>2015, ':month'=>$yourMonth),'選擇'='=>'user_id','組'=>'user_id','訂單'=>'COUNT(*) DESC','限制' =>5));$this->render('allstats', array("user"=>$user));}
這是我的視圖文件
<?phpforeach($user 作為 $show){for($i = 1 ; $i <=12 ; $i++){if($yourMonth == $i){$model = User::model()->findByAttributes(array('id'=>$show->user_id,));如果(isset($模型)){回聲'<h3>'.$show->user_id .' - ' .$model->用戶名.'</h3>';}別的 {回聲'<h3>'.$show->user_id .' - 未找到用戶名</h3>';}}}}?>
你可以起訴這個查詢獲得用戶的年度
$user=UserJoinEvent::model()->findAll(array('條件' =>'YEAR(date_create)=:year','參數(shù)' =>數(shù)組(':year'=>2015)'選擇'='=>'user_id','組'=>'user_id','訂單'=>'COUNT(*) DESC','限制' =>5));
并且對于這個月,您可以使用此查詢從 1 到 12 進行循環(huán),并使用循環(huán)中的值設(shè)置 $yourMonth
$user=UserJoinEvent::model()->findAll(array('條件' =>'YEAR(date_create)=:year 和 MONTH(date_create)=:month','參數(shù)' =>數(shù)組(':year'=>2015, ':month'=>$yourMonth)'選擇'='=>'user_id','組'=>'user_id','訂單'=>'COUNT(*) DESC','限制' =>5));
控制器動作
公共函數(shù) actionAllstats(){$this->layout='main';$myCurrYear = 日期(Y")$userYear=UserJoinEvent::model()->findAll(array('條件' =>'YEAR(date_create)=:year','參數(shù)' =>數(shù)組(':year'=>$myCurrYear)'選擇'='=>'user_id','組'=>'user_id','訂單'=>'COUNT(*) DESC','限制' =>5));$this->render('allstats', array("userYear"=>$userYear));}
查看
這個視圖不是基于良好的實踐,因為在視圖中使用了對模型的訪問.是為了引導(dǎo)您了解與問題相關(guān)的一些問題的嘗試.
<?php//這十二個月for($month = 1 ; $month <=12 ; $month++) {<div>$user=UserJoinEvent::model()->findAll(array('條件' =>'YEAR(date_created)=:year 和 MONTH(date_created)=:month','參數(shù)' =>數(shù)組(':year'=>2015, ':month'=>$month),'選擇'='=>'user_id','組'=>'user_id','訂單'=>'COUNT(*) DESC','限制' =>5));foreach($user as $show) {$model = User::model()->findByAttributes(array('id'=>$show->user_id,));如果(isset($模型)){回聲'<h3>'.$show->user_id .' - ' .$model->用戶名.'</h3>';}別的 {回聲'<h3>'.$show->user_id .' - 未找到用戶名</h3>';}}