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

在指令和类指令表中有很多行, 我想要的是,likes从类指令表中按 desc 顺序获取计数。 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 
4

2 回答 2

0

虽然您确实想按 分组instrunction_id,但您不想按此排序。相反,您想通过以下方式订购COUNT(instrunction_id)

$this->db->order_by('COUNT(instrunctionlike.instrunction_id)', 'DESC');
$this->db->group_by("instrunctionlike.instrunction_id"); 
于 2013-05-15T07:06:47.870 回答
0

请试试这个 My 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
于 2013-05-15T07:17:06.697 回答