简体   繁体   English

将Sql查询转换为CodeIgniter Active Records

[英]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: 这是我要转换为CodeIgnitor的Active Records的SQL查询:

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; 您的SQL语法有错误; 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 查看与您的MySQL服务器版本对应的手册,以便在'like)附近使用正确的语法作为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

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 `` . 请注意,您使用保留关键字,所以应该用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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