2013-05-15 137 views
0

我有兩個表遞減順序,笨:無法顯示的結果與數

instructions 
------------- 
instruction_id int(11) Primary key (Auto_increment) 
instruction  text 
user_id   int(11) Foreign key 


instrunctionlike 
----------------- 
instrunction_likeid int(11) Primary key (Auto_increment) 
instrunction_id  int(11) Foreign Key 

在說明&在instrunctionlike表有很多行, 我想要的是,獲得likes計數從類似instrunction的表中順序排列。 eg. select*from instrunctionlike order by count(instrunctionlike.instrunction_likeid)...

下面是我嘗試過,但我很困惑如何實現與desc順序的行計數。 請幫我解決這個問題

//----------------------------------------------------------------------------------- 
public function fetch_agreed_desc_order_instruction($limit, $start) { 
    $this->load->database(); 
    $this->db->limit($limit, $start); 
    $this->db->join('userdetails', 'userdetails.user_id = instructions.user_id'); 
     $this->db->join('instrunctionlike', 'instrunctionlike.instrunction_id = instructions.instruction_id'); 
    $this->db->order_by('instrunctionlike.instrunction_id', 'DESC'); 
    $this->db->group_by("instrunctionlike.instrunction_id"); 
    $query = $this->db->get("instructions"); 
    if ($query->num_rows() > 0) { 
     foreach ($query->result() as $row) { 
      $data[] = $row; 
     } 
     return $data; 
    } 
    return false; 
} 

輸出示例:

   instructions    Likes 
      .............    78 
      .............    66 
      .............    56 
      .............    34 
      .............    12 
      .............     1 
      .............     1 
      .............     0 
+0

Actully,從我瞭解的問題,你希望用戶的列表,他喜歡以降序計數。對? – Rajnish

+0

@Rajnish是的,你是對的。 –

+0

請張貼一些樣本數據和期望的輸出 –

回答

0

Whlie你通過instrunction_id想組,你不想通過訂購。你不是想COUNT(instrunction_id)訂購:

$this->db->order_by('COUNT(instrunctionlike.instrunction_id)', 'DESC'); 
$this->db->group_by("instrunctionlike.instrunction_id"); 
+0

謝謝。很簡單,我是一個愚蠢的傢伙。 –

+0

一個新的疑問:我想包含另一個條件。 '計數(喜歡)> 0'。爲此,我嘗試了'$ this-> db-> where('COUNT(instrunctionlike.instrunction_id)','0');'但它不起作用。爲什麼? –

+0

這將檢查'WHERE COUNT(instrunction_id)= 0'。你想要做'$ this-> db-> where('COUNT(instrunctionlike.instrunction_id)>',0)' – xbonez

0

請試試這個我的SQL查詢::

SELECT intruct.user_id, intruct.instruction, 
     count(ins_like.instrunction_likeid) AS cntlikes 

FROM `instrunctionlike` AS ins_like 

JOIN instructions AS intruct 
    where intruct.instruction_id = ins_like.instrunction_id 

GROUP BY ins_like.instrunction_likeid 
ORDER BY cntlikes DESC