将Sql查询转换为CodeIgniter Active Records

时间:2015-05-07 04:50:12

标签: php codeigniter

我只想查询那些喜欢最高的项目。

这是我要转换为CodeIgnitor的Active Records的SQL查询:

SELECT *, SUM(like) as totalLikes
FROM tbl_like
GROUP BY uploadID
ORDER BY totalLikes DESC
LIMIT 2

public function get_cheezyPic(){
      $this->db->select('uploadID, SUM(like) as totalLikes');
      $this->db->from('tbl_like');
      $this->db->group_by('uploadID');
      $this->db->order_by('totalLikes DESC');
      $this->db->limit(2);

      $query= $this->db->get();

      return $query->result_array();}

但是当我尝试运行此代码时,我遇到了此错误

  

您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在“喜欢”附近使用正确的语法作为totalLikes FROM(tbl_like)GROUP BY uploadID ORDER BY totalLikes'在第1行

SELECT `uploadID`, SUM(like) as totalLikes FROM (`tbl_like`) GROUP BY `uploadID` ORDER BY `totalLikes` desc LIMIT 2

这段代码出了什么问题?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这对你有用。请注意,您使用的是保留关键字,因此应附上 backtic ``

public function get_cheezyPic(){
      $this->db->select('uploadID, SUM(`like`) as totalLikes',false);
      $this->db->from('tbl_like');
      $this->db->group_by('uploadID');
      $this->db->order_by('totalLikes DESC');
      $this->db->limit(2);

      $query= $this->db->get();

      return $query->result_array();
}