Codeigniter:无法以计数显示desc顺序的结果

时间:2013-05-15 06:41:54

标签: mysql codeigniter

我有两张桌子,

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

指示&在类似于instrunction的表中有很多行, 我想要的是,从类似于instrunction的表中以desc顺序获取likes计数。   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 

2 个答案:

答案 0 :(得分:0)

虽然您确实希望按instrunction_id分组,但您不想按此排序。您想要按COUNT(instrunction_id)订购:

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

答案 1 :(得分:0)

请尝试使用My SQL Query ::

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