简体   繁体   中英

Converting Sql query to CodeIgniter Active Records

I wanted to query only those items that have a highest likes.

This is the sql query I want to convert into CodeIgnitor's Active Records:

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

CodeIgniter:

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();}

But when I try to run this code, I've got this error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'like) as totalLikes FROM ( tbl_like ) GROUP BY uploadID ORDER BY totalLikes ' at line 1

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

What's wrong with this code?

Thanks for the help.

This'll work for you. Please note that you were using reserved keyword so it should be enclosed with 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM